/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-07 19:44:55
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.bp.service.impl;

import cn.afterturn.easypoi.entity.ImageEntity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.io.ByteStreams;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.joysuch.wwyt.api.dataaccess.DataAccessService;
import com.joysuch.wwyt.bp.bean.*;
import com.joysuch.wwyt.bp.bean.MhRiskBroadcastBean.Item;
import com.joysuch.wwyt.bp.bean.MhRiskBroadcastBean.SafetyWorkCertStats;
import com.joysuch.wwyt.bp.bean.safetyworkcert.*;
import com.joysuch.wwyt.bp.entity.*;
import com.joysuch.wwyt.bp.entity.dsl.QBpWorkSafetyCert;
import com.joysuch.wwyt.bp.enums.*;
import com.joysuch.wwyt.bp.repository.*;
import com.joysuch.wwyt.bp.service.*;
import com.joysuch.wwyt.core.bean.BaseAttachmentBean;
import com.joysuch.wwyt.core.bean.SimpleSelectListBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.*;
import com.joysuch.wwyt.core.common.util.PageDataUtils.PageDataConvert;
import com.joysuch.wwyt.core.entity.BaseImageRepository;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.enums.RiskLevels;
import com.joysuch.wwyt.core.exception.BusinessRestrictionsException;
import com.joysuch.wwyt.core.repository.BaseImageRespositoryDao;
import com.joysuch.wwyt.core.repository.BaseTypeGroupItemDao;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseAttachmentRepositoryService;
import com.joysuch.wwyt.core.service.BaseTypeGroupItemService;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.edu.entity.EduCertificate;
import com.joysuch.wwyt.edu.entity.EduCertificateUser;
import com.joysuch.wwyt.edu.repository.EduCertificateDao;
import com.joysuch.wwyt.edu.repository.EduCertificateUserDao;
import com.joysuch.wwyt.mh.bean.CertSummaryDto;
import com.joysuch.wwyt.monitoringcenter.service.impl.MonitoringCenterServiceImpl;
import com.joysuch.wwyt.risk.bean.RiskPointControlRiskListSearchBean;
import com.joysuch.wwyt.risk.bean.RiskPointInDistrictListBean;
import com.joysuch.wwyt.risk.entity.*;
import com.joysuch.wwyt.risk.repository.RiskDistrictDao;
import com.joysuch.wwyt.risk.repository.RiskEvaluationRepoDao;
import com.joysuch.wwyt.risk.repository.RiskPointDao;
import com.joysuch.wwyt.risk.repository.RiskPointEvaluationJhaDao;
import com.joysuch.wwyt.risk.service.RiskEvaluationRepoService;
import com.joysuch.wwyt.risk.service.RiskPointService;
import com.joysuch.wwyt.risk.util.RiskPointUtil;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.Assert;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.geo.Point;
import org.springframework.stereotype.Service;

import javax.persistence.Tuple;
import javax.transaction.Transactional;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class BpWorkSafetyCertServiceImpl implements BpWorkSafetyCertService {

    @Autowired
    private BpTaskListService taskListService;
    @Autowired
    private BpWorkSafetyCertDao dao;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;
    @Autowired
    private RiskDistrictDao riskDistrictDao;
    @Autowired
    private RiskPointDao riskPointDao;
    @Autowired
    private RiskPointService riskPointService;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private BaseAttachmentRepositoryService attachmentRepositoryService;
    @Autowired
    private BaseTypeGroupItemService baseTypeGroupItemService;
    @Autowired
    private BpWorkSafetyCertMethodDao bpWorkSafetyCertMethodDao;
    @Autowired
    private BpWorkSafetyCertUserDao bpWorkSafetyCertUserDao;
    @Autowired
    private BpWorkSafetyCertUserService bpWorkSafetyCertUserService;
    @Autowired
    private BpWorkSafetyCertMethodService bpWorkSafetyCertMethodService;
    @Autowired
    private BaseAttachmentRepositoryService baseAttachmentRepositoryService;
    @Autowired
    private BpTaskListDao taskListDao;
    @Autowired
    private RiskEvaluationRepoService riskEvaluationRepoService;
    @Autowired
    private BpCertificateService certificateService;
    @Autowired
    private BpWorkSafetyCertDao bpWorkSafetyCertDao;
    @Autowired
    private RiskPointEvaluationJhaDao evaluationJhaDao;
    @Autowired
    private EduCertificateDao eduCertificateDao;
    @Autowired
    private BpWorkSafetyIdentifyDao bpWorkSafetyIdentifyDao;
    @Autowired
    private BpWorkSafetySigenerDao bpWorkSafetySigenerDao;
    @Autowired
    private BpWorkSafetyFileAnalyzeDao bpWorkSafetyFileAnalyzeDao;
    @Autowired
    private BpWorkSafetySpaceAnalyzeDao bpWorkSafetySpaceAnalyzeDao;
    @Autowired
    private RiskEvaluationRepoDao riskEvaluationRepoDao;
    @Autowired
    private BpWorkSafetyAuditTemplateDao bpWorkSafetyAuditTemplateDao;
    @Autowired
    private BpJobDao bpJobDao;
    @Autowired
    private BpWorkSafetyAuditProcessDao bpWorkSafetyAuditProcessDao;
    @Autowired
    private BpWorkSafetyAuditProcessDetailDao bpWorkSafetyAuditProcessDetailDao;
    @Autowired
    private BpContractorStaffService bpContractorStaffService;
    @Autowired
    private BpContractorDao bpContractorDao;
    @Autowired
    private EduCertificateUserDao eduCertificateUserDao;
    @Autowired
    private BaseImageRespositoryDao baseImageRespositoryDao;
    @Autowired
    private BpWorkSafetyMethodConfigDao bpWorkSafetyMethodConfigDao;
    @Autowired
    private BpWorkSafetyCertTypeDao bpWorkSafetyCertTypeDao;
    @Autowired
    private DataAccessService dataAccessService;
    @Autowired
    private BpContractorStaffDao bpContractorStaffDao;
    @Autowired
    private BaseTypeGroupItemDao baseTypeGroupItemDao;
    @Autowired
    private MonitoringCenterServiceImpl monitoringCenterService;

    @Value("${wwyt.base.serverUrl}")
    private String serverUrl;


    @Override
    public BpWorkSafetyCert addFireCert(BpWorkSafetyApplyFireAddBean entity) {
        BpWorkSafetyCert content = null;
        BpWorkSafetyCert save = null;
        try {
            validateStartAndEndTime(entity.getStartTime(), entity.getEndTime());
            content = new BpWorkSafetyCert();
            // 作业证编号
            if (StringUtils.isBlank(entity.getCode())) {
                content.setCode(bizCodeGeneratorFacade.dongHuoZuoYe());
            } else {
                content.setCode(entity.getCode());
            }
            // 作业类型
            content.setType(SafetyWorkTypes.DONG_HUO.getName());
            // 作业级别
            content.setWorkLevel(entity.getWorkLevel());
            // 作业开始时间
            content.setStartTime(entity.getStartTime());
            // 作业结束时间
            content.setEndTime(entity.getEndTime());
            // 设置报警
            content.setAlarm(entity.getAlarm());
            if (entity.getApplyTime() == null) {
                content.setApplyTime(new Date());
            } else {
                content.setApplyTime(entity.getApplyTime());
            }
            // 状态
            if (entity.getFlag() != null && entity.getFlag() == 0) {
                //作业证app申请完成后,状态为待审核
                content.setState(SafetyWorkStates.WAITING_FOR_AUDIT.getId());
            } else {
                content.setState(SafetyWorkStates.INITIAL.getId());
            }
            // 申请单位
            content.setApplyDepartId(entity.getApplyDepartId());
            // 申请人
            content.setApplyUserId(entity.getApplyUserId());
            // 所属风险区域
            content.setRiskDistrictId(entity.getRiskDistrictId());
            // 作业区域地点
            if (entity.getFlag() != null && entity.getFlag() == 0) {
                //app作业区域
                content.setLocationCoords(getAppCoordinateString(entity.getRiskDistrictId()));
            } else {
                content.setLocationCoords(entity.getLocationCoords());
            }
            // 作业内容
            content.setWorkContent(entity.getOpFireContent());
            // 监护人
            content.setMonitorUserCode(entity.getOpFireMonitorUserId());
            // 实施安全教育人
            content.setEducationUserCode(entity.getOpFireEducationUserId());
            // 风险点
            content.setRiskPointId(entity.getRiskPointId());
            // 风险级别
            content.setRiskLevel(entity.getRiskLevel());
            // 附件ID
            if (entity.getAttachment() != null) {
                content.setAttachmentId(entity.getAttachment().getId());
            }
            //作业地点
            content.setJobSite(entity.getJobSite());
            // 危害辨识
            content.setDangerRecoganize(entity.getDangerRecoganize());
            // 编制人
            content.setEditUserId(entity.getEditUserId());
            //涉及的其他作业证
            if (!CollectionUtils.isEmpty(entity.getOtherSpecialWorkId())) {
                content.setOtherSpecialWorkId(JSON.toJSONString(entity.getOtherSpecialWorkId()));
            }
            BpWorkSafetyCertFireEditBean extraInfo = new BpWorkSafetyCertFireEditBean();
            extraInfo.setOpFireFirstAuditUserId(StringUtil.escapeNull(entity.getOpFireFirstAuditUserId()));
            extraInfo.setOpFireJobResponsibleUserId(StringUtil.escapeNull(entity.getOpFireJobResponsibleUserId()));
            //动火方式
            if (!CollectionUtils.isEmpty(entity.getOpFireMethodId())) {
                extraInfo.setOpFireMethodId(entity.getOpFireMethodId());
            }
            // extraInfo.setOpFireMethodName(null);
            extraInfo.setOpFireMonitorUserId(entity.getOpFireMonitorUserId());
            content.setWorkToolName(entity.getWorkToolName());
            extraInfo.setProductionDepartResponsibleUserId(
                    StringUtil.escapeNull(entity.getProductionDepartResponsibleUserId()));
            Gson gson = new Gson();
            content.setWorkOtherInfoEntityJson(gson.toJson(extraInfo));
            content.setJhaEvaluationId(entity.getJhaEvaluationId());
            //web存 app端申请不存
            //是否需要电子签章
            content.setNeedEletricityApplySheet(entity.getNeedEletricityApplySheet());
            //证书json
            //申请人证书ids
            if (!CollectionUtils.isEmpty(entity.getApplyUserCertIds())) {
                content.setApplyUserCertIdJson(JSON.toJSONString(entity.getApplyUserCertIds()));
            }

            //编制人证书ids
            if (!CollectionUtils.isEmpty(entity.getEditUserCertIds())) {
                content.setEditUserCertIdJson(JSON.toJSONString(entity.getEditUserCertIds()));
            }

            // 实施安全教育人
            if (!CollectionUtils.isEmpty(entity.getOpFireEducationUserCertIds())) {
                content.setEducationUserCertIdJson(JSON.toJSONString(entity.getOpFireEducationUserCertIds()));
            }

            //动火特有的人员证书ids
            WorkOtherUserCertIdDto workDto = new WorkOtherUserCertIdDto();
            // 生产单位负责人
            if (!CollectionUtils.isEmpty(entity.getProductionDepartResponsibleUserCertIds())) {
                workDto.setProductionDepartResponsibleUserCertIds(entity.getProductionDepartResponsibleUserCertIds());
            }
            // 动火初审人
            if (!CollectionUtils.isEmpty(entity.getOpFireFirstAuditUserCertIds())) {
                workDto.setOpFireFirstAuditUserCertIds(entity.getOpFireFirstAuditUserCertIds());
            }

            // 动火作业负责人
            if (!CollectionUtils.isEmpty(entity.getOpFireJobResponsibleUserCertIds())) {
                workDto.setOpFireJobResponsibleUserCertIds(entity.getOpFireJobResponsibleUserCertIds());
            }
            // 监火人
            if (!CollectionUtils.isEmpty(entity.getOpFireMonitorUserCertIds())) {
                workDto.setOpFireMonitorUserCertIds(entity.getOpFireMonitorUserCertIds());
            }
            if (workDto != null) {
                content.setWorkOtherUserCertIdJson(JSON.toJSONString(workDto));
            }
            //作业证人员分类
            if (entity.getPeopleTypeBean() != null) {
                content.setPeopleTypeJson(JSON.toJSONString(entity.getPeopleTypeBean()));
            }

            save = dao.save(content);
            //app申请后添加待办事项
            if (entity.getFlag() != null && entity.getFlag() == 0) {
                List<BpTaskList> byId = taskListService.findById(save.getId());
                if (byId != null) {
                    for (BpTaskList bpTaskList : byId) {
                        bpTaskList.setState(0);
                        bpTaskList.setDataId(save.getId());
                        bpTaskList.setDetail("作业证审批");
                        bpTaskList.setUserId(save.getApplyUserId());
                        taskListDao.save(bpTaskList);
                    }
                }
            }
            // 保存动火人相关信息
            saveOperatorUsers(content, entity.getOperatorUserCertDtos());
            // 保存安全措施
            saveOpMethods(save, entity.getSafetyMethods());
            //保存动火分析
            saveFileAnalyze(save, entity.getWebFileBeans());

            // 添加待办事项
            saveTaskList("动火安全作业证", save);
            if (entity.getJhaEvaluationId() != null) {
                // 将作业证和风险评估建立关联
                riskEvaluationRepoService.updateRelatedWorkSafetyCertInfo(entity.getJhaEvaluationId(), save.getId());
            }
            //保存危害辨识表
            saveIdentify(save, entity.getDangerRecoganize(), 0, "危害辨识");
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        //设置审核流程
        saveFirstProcess(save.getId());
        return save;
    }

    //获取app作业证地图作业区域-风险区域中心点+偏移量
    public String getAppCoordinateString(Long riskDistrictId) {
        if (riskDistrictId != null) {
            Optional<RiskDistrict> ord = riskDistrictDao.findById(riskDistrictId);
            MapUtils.ThreeDPoints points = MapUtils.parse3DPointsFromJson(ord.get().getCoordinates());
            MapUtils.SafetyPoints safetyPoints = new MapUtils.SafetyPoints();
            List<MapUtils.SafetyPoint> pointList = new ArrayList<>();
            if (points != null) {
                MapUtils.SafetyPoint wwytPoint = new MapUtils.SafetyPoint();
                Point centerPoint = MapUtils.calculateCenterPoint(points.getPoints());
                wwytPoint.setX(monitoringCenterService.offsetCoordinate(centerPoint.getX(), 0, 5, 0.00001));
                wwytPoint.setY(monitoringCenterService.offsetCoordinate(centerPoint.getY(), 0, 5, 0.00001));
                wwytPoint.setZ(0.00);
                wwytPoint.setFloorId(points.getFloorId());
                pointList.add(wwytPoint);
            }
            safetyPoints.setBuildingId("000000");
            safetyPoints.setPoints(pointList);
            return JSON.toJSONString(safetyPoints);
        } else {
            return null;
        }
    }

    // @Override
    public BpWorkSafetyCert updateFireCert(BpWorkSafetyApplyFireAddBean entity) throws Exception {
        BpWorkSafetyCert save = null;
        try {
            validateStartAndEndTime(entity.getStartTime(), entity.getEndTime());
            BpWorkSafetyCert content = dao.getOne(entity.getId());
            // 作业类型
            content.setType(SafetyWorkTypes.DONG_HUO.getName());
            // 作业级别
            content.setWorkLevel(entity.getWorkLevel());
            // 作业开始时间
            content.setStartTime(entity.getStartTime());
            // 作业结束时间
            content.setEndTime(entity.getEndTime());
            // 设置报警
            content.setAlarm(entity.getAlarm());
            if (entity.getApplyTime() == null) {
                content.setApplyTime(new Date());
            } else {
                content.setApplyTime(entity.getApplyTime());
            }
            // 申请单位
            content.setApplyDepartId(entity.getApplyDepartId());
            // 申请人
            content.setApplyUserId(entity.getApplyUserId());
            // 作业内容
            content.setWorkContent(entity.getOpFireContent());
            // 所属风险区域
            content.setRiskDistrictId(entity.getRiskDistrictId());
            // 作业区域地点
            if (entity.getFlag() != null && entity.getFlag() == 0) {
                //app作业区域
                content.setLocationCoords(getAppCoordinateString(entity.getRiskDistrictId()));
            } else {
                content.setLocationCoords(entity.getLocationCoords());
            }
            // 监护人
            content.setMonitorUserCode(entity.getOpFireMonitorUserId());
            // 实施安全教育人
            content.setEducationUserCode(entity.getOpFireEducationUserId());
            // 风险点
            content.setRiskPointId(entity.getRiskPointId());
            // 风险级别
            content.setRiskLevel(entity.getRiskLevel());
            // 附件ID
            if (entity.getAttachment() != null) {
                content.setAttachmentId(entity.getAttachment().getId());
            }
            //作业地点
            content.setJobSite(entity.getJobSite());
            // 危害辨识
            content.setDangerRecoganize(entity.getDangerRecoganize());
            // 编制人
            content.setEditUserId(entity.getEditUserId());
            //涉及的其他作业证
            content.setOtherSpecialWorkId(JSON.toJSONString(entity.getOtherSpecialWorkId()));
            BpWorkSafetyCertFireEditBean extraInfo = new BpWorkSafetyCertFireEditBean();
            extraInfo.setOpFireFirstAuditUserId(StringUtil.escapeNull(entity.getOpFireFirstAuditUserId()));
            extraInfo.setOpFireJobResponsibleUserId(StringUtil.escapeNull(entity.getOpFireJobResponsibleUserId()));
            //动火方式
            extraInfo.setOpFireMethodId(entity.getOpFireMethodId());
            content.setWorkToolName(entity.getWorkToolName());
            extraInfo.setOpFireMonitorUserId(entity.getOpFireMonitorUserId());
            extraInfo.setProductionDepartResponsibleUserId(
                    StringUtil.escapeNull(entity.getProductionDepartResponsibleUserId()));
            Gson gson = new Gson();
            content.setWorkOtherInfoEntityJson(gson.toJson(extraInfo));
            content.setJhaEvaluationId(entity.getJhaEvaluationId());

            // 2019-12-13添加
            //是否需用电申请签单
            content.setNeedEletricityApplySheet(entity.getNeedEletricityApplySheet());
            //证书json
            //申请人证书ids
            content.setApplyUserCertIdJson(JSON.toJSONString(entity.getApplyUserCertIds()));

            //编制人证书ids
            content.setEditUserCertIdJson(JSON.toJSONString(entity.getEditUserCertIds()));
            // 实施安全教育人
            content.setEducationUserCertIdJson(JSON.toJSONString(entity.getOpFireEducationUserCertIds()));
            //动火特有的人员证书ids
            WorkOtherUserCertIdDto workDto = new WorkOtherUserCertIdDto();
            // 生产单位负责人
            workDto.setProductionDepartResponsibleUserCertIds(entity.getProductionDepartResponsibleUserCertIds());
            // 动火初审人
            workDto.setOpFireFirstAuditUserCertIds(entity.getOpFireFirstAuditUserCertIds());
            // 动火作业负责人
            workDto.setOpFireJobResponsibleUserCertIds(entity.getOpFireJobResponsibleUserCertIds());
            // 监火人
            workDto.setOpFireMonitorUserCertIds(entity.getOpFireMonitorUserCertIds());

            content.setWorkOtherUserCertIdJson(JSON.toJSONString(workDto));
            //作业证人员分类
            content.setPeopleTypeJson(JSON.toJSONString(entity.getPeopleTypeBean()));
            //删除危害辨识表
            bpWorkSafetyIdentifyDao.deleteByCertId(content.getId());
            save = dao.save(content);

            bpWorkSafetyCertMethodDao.deleteByWorkId(content.getId());
            bpWorkSafetyCertUserDao.deleteByWorkId(content.getId());

            //删除安全措施确认表
            bpWorkSafetySigenerDao.deleteByCertIdAndCategoryId(content.getId(), 1);
            //删除动火分析表
            bpWorkSafetyFileAnalyzeDao.deleteByCertId(content.getId());

            // 保存动火人相关信息
            saveOperatorUsers(content, entity.getOperatorUserCertDtos());
            // 保存安全措施
            saveOpMethods(content, entity.getSafetyMethods());
            //保存动火分析表
            saveFileAnalyze(content, entity.getWebFileBeans());
            // 修改待办事项
            saveTaskList("动火安全作业证", save);
            //保存危害辨识表
            saveIdentify(save, entity.getDangerRecoganize(), 0, "危害辨识");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        //设置审核流程
        saveFirstProcess(save.getId());
        return save;
    }

    //保存危害辨识表
    private void saveIdentify(BpWorkSafetyCert cert, String dangerRecoganize, Integer categoryId, String content) {
        BpWorkSafetyIdentify identify = new BpWorkSafetyIdentify();
        identify.setCertId(cert.getId());
        identify.setType(cert.getType());
        identify.setContent(dangerRecoganize);
        bpWorkSafetyIdentifyDao.save(identify);
    }

    /**
     * 保存安全措施
     *
     * @param content       动火操作实体
     * @param safetyMethods 安全操作
     */
    private void saveOpMethods(BpWorkSafetyCert content, List<BpWorkSafetyApplyMethodAddBean> safetyMethods) {
        if (safetyMethods != null && safetyMethods.size() > 0) {
            for (BpWorkSafetyApplyMethodAddBean bean : safetyMethods) {
                BpWorkSafetyCertMethod entity = new BpWorkSafetyCertMethod();
                entity.setWorkId(content.getId());
                entity.setConfirmUserId(bean.getConfirmUserId());
                entity.setMethod(bean.getMethod());
                entity.setState(bean.getState());
                entity.setConfirmUserType(bean.getUserType());
                List<Long> confirmUserCertIds = bean.getConfirmUserCertIds();
                if (confirmUserCertIds == null) {
                    confirmUserCertIds = Lists.newArrayList();
                }
                entity.setConfirmUserCertIdJson(JSON.toJSONString(confirmUserCertIds));
                //将措施保存到措施确认表中
                BpWorkSafetySigener sigener = new BpWorkSafetySigener();
                sigener.setCategoryId(1);
                sigener.setContent(bean.getMethod());
                sigener.setCertId(content.getId());
                sigener.setType(content.getType());
//                sigener.setUserId(bean.getConfirmUserId());
                BpWorkSafetySigenerListBean listBean = new BpWorkSafetySigenerListBean();
                List<BpWorkSafetySigenerJsonBean> jsonBeans = new ArrayList<>();
                BpWorkSafetySigenerJsonBean jsonBean = new BpWorkSafetySigenerJsonBean();
                jsonBean.setUserId(bean.getConfirmUserId());
                jsonBeans.add(jsonBean);
                listBean.setJsonBeans(jsonBeans);
                sigener.setSignerJson(JSON.toJSONString(listBean));

                BpWorkSafetySigener save = bpWorkSafetySigenerDao.save(sigener);
                entity.setSingerId(save.getId());
                bpWorkSafetyCertMethodDao.save(entity);
            }
        }
    }

    /**
     * 保存操作人信息
     */
    private void saveOperatorUsers(BpWorkSafetyCert content, List<OperatorUserCertDto> dtoList) {
        if (dtoList == null) {
            return;
        }
        for (OperatorUserCertDto userCertDto : dtoList) {
            BpWorkSafetyCertUser u = new BpWorkSafetyCertUser();
            String type = userCertDto.getUserType();
            if (type != null) {
                UserTypes userType = UserTypes.findByCode(type);
                Assert.notNull(userType, "不能识别的人员类型");
                setUserDepartAndCertInfo(u, userType);
            }


            Long uid = userCertDto.getUserId();
            Assert.notNull(uid, "人员id不能为空");
            u.setOpUserCode(String.valueOf(uid));
            // 设置单位、证书信息
            u.setWorkId(content.getId());
            BaseUser user = null;
            //人员是承包商
            if (userCertDto.getPeopleType() != null && userCertDto.getPeopleType() == 1) {
                EduCertificateUser eUser = eduCertificateUserDao.findByUserId(uid);
                if (eUser != null && eUser.getCertId() != null) {
                    u.setCertName(eduCertificateDao.getNameById(eUser.getCertId()));
                }
            } else {
                user = baseUserDao.findById(uid).orElse(null);
                if (user != null) {
                    u.setDepartCode(String.valueOf(user.getDepartId()));
                    u.setDepartName(bpDepartDao.findDepartNameById(user.getDepartId()));
                    u.setCertName(certificateService.findCertNameByUserIdAndType(user.getId(), WorkCertificateTypes.TE_ZHONG_ZUO_YE.getCode()));
                }
            }

            //人员证书
            if (!CollectionUtils.isEmpty(userCertDto.getOperatorUserCertIds())) {
                u.setOperatorUserCertIdJson(JSON.toJSONString(userCertDto.getOperatorUserCertIds()));
            }
            u.setUserType(userCertDto.getPeopleType());
            bpWorkSafetyCertUserDao.save(u);
        }

//        if (people != null && people.size() > 0) {
//            for (String uid : people) {
//                BpWorkSafetyCertUser u = new BpWorkSafetyCertUser();
//                if (uid.contains("_")) {
//                    String[] ss = uid.split("_");
//                    UserTypes userType = UserTypes.findByCode(ss[0]);
//                    Assert.notNull(userType, "不能识别的人员类型");
//                    // u.setCertName(uid);
//                    setUserDepartAndCertInfo(u, userType);
//                } else {
//
//                }
//                u.setOpUserCode(uid);
//                // 设置单位、证书信息
//                u.setWorkId(content.getId());
//                try {
//                    BaseUser user = baseUserDao.findById(Long.valueOf(uid)).orElse(null);
//                    if (user != null) {
//                        u.setDepartCode(user.getDepartId() + "");
//                        u.setDepartName(bpDepartDao.findDepartNameById(user.getDepartId()));
//                        u.setCertName(certificateService.findCertNameByUserIdAndType(user.getId(),
//                                WorkCertificateTypes.TE_ZHONG_ZUO_YE.getCode()));
//                    }
//                } catch (Exception e) {
//                }
//                bpWorkSafetyCertUserDao.save(u);
//                // u.setType();
//            }
//        }
    }

    //保存动火分析作业
    private void saveFileAnalyze(BpWorkSafetyCert content, List<BpWorkSafetyWebFileBean> webFileBeans) {
        if (!CollectionUtils.isEmpty(webFileBeans)) {
            for (BpWorkSafetyWebFileBean bean : webFileBeans) {
                BpWorkSafetyFileAnalyze analyze = new BpWorkSafetyFileAnalyze();
                BeanUtils.copyProperties(bean, analyze);
                analyze.setOtherCert(bean.getOtherCert());
                analyze.setCertId(content.getId());
                analyze.setType(content.getType());
                analyze.setUserType(bean.getUserType());
                //保存动火分析人签名
//                Long sId = saveSinger(content, bean.getUserId(), 2, "分析人");
//                analyze.setSignerId(sId);
                bpWorkSafetyFileAnalyzeDao.save(analyze);
            }
        }
    }

    // 设置操作人单位、证书信息
    private void setUserDepartAndCertInfo(BpWorkSafetyCertUser u, UserTypes userType) {
        if (userType == UserTypes.CONTRACTOR) {
            // 设置承包商信息
        } else {
            // Long departId = baseUserDao.getOne(u.getOpUserId()).getDepartId();
            // u.setDepartId(departId);
        }
    }

    // 修改
    @Override
    public BpWorkSafetyCert update(BpWorkSafetyCertEditBaseBean entity, SafetyWorkTypes type, String module) throws Exception {
        BpWorkSafetyCert save = null;
        try {
            validateStartAndEndTime(entity);
            BpWorkSafetyCert content = dao.findById(entity.getId()).get();
            content.setType(type.getName());
            // 作业级别
            content.setWorkLevel(entity.getWorkLevel());
            // 作业开始时间
            content.setStartTime(entity.getStartTime());
            // 作业结束时间
            content.setEndTime(entity.getEndTime());
            if (entity.getApplyTime() == null) {
                content.setApplyTime(new Date());
            } else {
                content.setApplyTime(entity.getApplyTime());
            }
            content.setAlarm(entity.getAlarm());
            // 状态
            content.setState(SafetyWorkStates.INITIAL.getId());
            // 申请单位
            content.setApplyDepartId(entity.getApplyDepartId());
            // 申请人
            content.setApplyUserId(entity.getApplyUserId());
            // 作业内容
            content.setWorkContent(entity.getWorkContent());
            // 所属风险区域
            content.setRiskDistrictId(entity.getRiskDistrictId());
            // 作业区域地点
            if (entity.getFlag() != null && entity.getFlag() == 0) {
                //app作业区域
                content.setLocationCoords(getAppCoordinateString(entity.getRiskDistrictId()));
            } else {
                content.setLocationCoords(entity.getLocationCoords());
            }
            // 监护人
            content.setMonitorUserCode(entity.getMonitorUserCode());
            // 实施安全教育人
            content.setEducationUserCode(entity.getEducationUserCode());
            // 风险点
            content.setRiskPointId(entity.getRiskPointId());
            // 风险级别
            content.setRiskLevel(entity.getRiskLevel());
            // 附件ID
            if (entity.getAttachment() != null) {
                content.setAttachmentId(entity.getAttachment().getId());
            }
            //作业地点
            content.setJobSite(entity.getJobSite());
            // 危害辨识
            content.setDangerRecoganize(entity.getDangerRecoganize());
            // 编制人
            content.setEditUserId(entity.getEditUserId());
            //涉及的其他作业证
            content.setOtherSpecialWorkId(JSON.toJSONString(entity.getOtherSpecialWorkId()));
            content.setWorkToolName(entity.getWorkToolName());
            content.setJhaEvaluationId(entity.getJhaEvaluationId());
            content.setNeedEletricityApplySheet(entity.getNeedEletricityApplySheet());
            //编制人证书
            content.setEditUserCertIdJson(JSON.toJSONString(entity.getEditUserCertIds()));
            //申请人证书
            content.setApplyUserCertIdJson(JSON.toJSONString(entity.getApplyUserCertIds()));
            //监护人证书
            content.setMonitorUserCertIdJson(JSON.toJSONString(entity.getMonitorUserCertIds()));
            //实施安全教育人证书
            content.setEducationUserCertIdJson(JSON.toJSONString(entity.getEducationUserCertIds()));
            setExtraInfo(content, entity, type);
            //作业证人员分类
            content.setPeopleTypeJson(JSON.toJSONString(entity.getPeopleTypeBean()));
            save = dao.save(content);
            //删除危害辨识表
            bpWorkSafetyIdentifyDao.deleteByCertId(content.getId());
            bpWorkSafetyCertMethodDao.deleteByWorkId(content.getId());
            bpWorkSafetyCertUserDao.deleteByWorkId(content.getId());
            //删除受限空间分析表
            bpWorkSafetySpaceAnalyzeDao.deleteByCertId(content.getId());
            //删除安全措施确认表
            bpWorkSafetySigenerDao.deleteByCertIdAndCategoryId(content.getId(), 1);
//            if (type == SafetyWorkTypes.MANG_BAN_CHOU_DU) {
//                //保存盲板抽堵操作人信息
//                saveMangBanChouDuPeople(content, entity);
//            } else {
//                // 保存操作人相关信息
            saveOperatorUsers(content, entity.getOperatorUserCertDtos());
//            }
            // 保存安全措施
            saveOpMethods(content, entity.getSafetyMethods());
            //保存受限空间分析
            if (type == SafetyWorkTypes.SHOU_XIAN_KONG_JIAN) {
                saveWebSpaceAnalyze(content, entity.getWebSpaceBeans());
            }
            //保存危害辨识表
            saveIdentify(content, entity.getDangerRecoganize(), 0, "危害辨识");
            // 修改代办事项
            List<BpTaskList> byId = taskListService.findById(save.getId());
            if (byId != null) {
                for (BpTaskList bpTaskList : byId) {
                    bpTaskList.setDataId(save.getId());
                    bpTaskList.setUserId(save.getApplyUserId());
                    bpTaskList.setState(save.getState());
                    bpTaskList.setModule(module);
                    taskListDao.save(bpTaskList);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        //设置审核流程
        saveFirstProcess(save.getId());
        return save;
    }

    @Override
    public Page<BpWorkSafetyApplyFireListBean> findByPage(Pageable page, BpWorkSafetyCertSearchBean condition,
                                                          SafetyWorkTypes type) {
        page = PageDataUtils.addOrderByDesc(page, "code");
        Predicate predicate = prepareListSearchCondition(condition, type);
        Page<BpWorkSafetyCert> data = predicate == null ? dao.findAll(page) : dao.findAll(predicate, page);

        return PageDataUtils.convertPageData(data,
                new PageDataConvert<BpWorkSafetyApplyFireListBean, BpWorkSafetyCert>() {

                    @Override
                    public BpWorkSafetyApplyFireListBean convert(BpWorkSafetyCert f) {
                        BpWorkSafetyApplyFireListBean bean = new BpWorkSafetyApplyFireListBean();

                        // ID
                        bean.setId(f.getId());
                        // 作业证编号
                        bean.setCode(f.getCode());
                        // 作业类型
                        bean.setType(f.getType());
                        // 作业级别
                        bean.setWorkLevel(f.getWorkLevel());
                        // bean.setWorkLevelName(OpFireWorkLevels.findNameById(f.getWorkLevel()));
                        if ("动火".equals(f.getType()) && f.getWorkLevel() == 0) {
                            bean.setWorkLevelName("特殊危险");
                        }
                        // 状态
                        bean.setState(f.getState());
                        bean.setStateName(SafetyWorkStates.findNameById(f.getState()));

                        // 所属风险区域
                        bean.setRiskDistrictId(f.getRiskDistrictId());
                        if (f.getRiskDistrictId() != null) {
                            bean.setRiskDistrictName(riskDistrictDao.findNameById(f.getRiskDistrictId()));
                        }

                        // 工作内容
                        bean.setWorkContent(f.getWorkContent());
                        // 工作时间
                        bean.setWorkTime(parseWorkTime(f));
                        // 申请时间
                        bean.setApplyTime(SimpleDateFormatCache.getYmdZC().format(f.getApplyTime()));
                        if (f.getState() != null && f.getState() == 3) {
                            // 审核失败
                            bean.setAuditMsg(f.getAuditMsg());
                            bean.setAuditUser(baseUserDao.getBaseUserNameById(f.getAuditUserId()));
                        }

                        if (type == SafetyWorkTypes.LIN_SHI_YONG_DIAN) {
                            // 填充用电功率计设备信息
                            setTempElectricityListInfo(bean, f);
                        }
                        if (type == SafetyWorkTypes.YI_BAN) {
                            setYiBanZuoYeJobTypeInfO(bean, f);
                        }
                        bean.setJhaEvaluationId(f.getJhaEvaluationId());
                        return bean;
                    }

                });
    }

    protected void setTempElectricityListInfo(BpWorkSafetyApplyFireListBean bean, BpWorkSafetyCert f) {
        BpWorkSafetyCertTempElectricityEditBean info = parse(BpWorkSafetyCertTempElectricityEditBean.class,
                f.getWorkOtherInfoEntityJson());
        bean.setDeviceAndPower(info.getDeviceAndPower());
    }

    protected void setYiBanZuoYeJobTypeInfO(BpWorkSafetyApplyFireListBean bean, BpWorkSafetyCert f) {
        BpWorkSafetyCertYiBanEditBean info = parse(BpWorkSafetyCertYiBanEditBean.class, f.getWorkOtherInfoEntityJson());
        bean.setJobType(parseJobTypeName(info.getJobType()));
    }

    protected String parseJobTypeName(String jobType) {
        if ("1".equals(jobType)) {
            return "脚手架搭设/拆除作业";
        } else if ("2".equals(jobType)) {
            return "检维修作业或新建作业";
        } else if ("0".equals(jobType)) {
            return "其它";
        }
        return "";
    }

    private Predicate prepareListSearchCondition(BpWorkSafetyCertSearchBean condition, SafetyWorkTypes type) {
        QBpWorkSafetyCert cert = QBpWorkSafetyCert.bpWorkSafetyCert;
        Predicate p = cert.type.eq(type.getName());
        p = ExpressionUtils.and(p, cert.createBy.eq(Context.getCurrentUserId()));
        if (condition.getState() != null) {
            p = ExpressionUtils.and(p, cert.state.eq(condition.getState()));

        }
        //zzz
        if (condition.getCodeOr() != null) {
            if (type == SafetyWorkTypes.DONG_HUO) {
                Integer level = RiskPointUtil.findWorkLevelFromText(condition.getCodeOr());
                Predicate p2 = cert.code.like("%" + condition.getCodeOr() + "%");
                if (level != null) {
                    p2 = ExpressionUtils.or(p2, cert.workLevel.eq(level));
                }
                p = ExpressionUtils.and(p, p2);
            } else if (type == SafetyWorkTypes.MANG_BAN_CHOU_DU) {
                // 编号，管道名称
                Predicate p2 = ExpressionUtils.or(cert.workContent.like("%" + condition.getCodeOr() + "%"),
                        cert.code.like("%" + condition.getCodeOr() + "%"));
                p = ExpressionUtils.and(p, p2);
            } else {
                p = ExpressionUtils.and(p, cert.code.like("%" + condition.getCodeOr() + "%"));
            }

        }
        return p;

    }

    @Override
    public void delete(Long id) throws BusinessRestrictionsException {
        // 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用。不能删除时将抛出业务异常
        checkBussinessRestrictions(id);
        dao.deleteById(id);
    }

    /**
     * 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用
     *
     * @param id 要删除的业务ID
     *           //* @throws BussinessRestrictionsException.
     *           抛出的业务异常
     */
    private void checkBussinessRestrictions(Long id) throws BusinessRestrictionsException {

    }

    @Override
    public BpWorkSafetyCert findById(Long id) {
        return dao.findById(id).get();
    }

    @Override
    public BpWorkSafetyCertDetailBean getById(Long id) {
        BpWorkSafetyCert entity = findById(id);
        BpWorkSafetyPeopleTypeBean peopleTypeBean = null;
        if (StringUtils.isNotBlank(entity.getPeopleTypeJson())) {
            peopleTypeBean = JSONObject.parseObject(entity.getPeopleTypeJson(), BpWorkSafetyPeopleTypeBean.class);
        }
        BpWorkSafetyCertDetailBean bean = createDetailBeanByType(entity);
        //人员分类
        bean.setPeopleTypeBean(peopleTypeBean);
        // ID
        bean.setId(entity.getId());
        // 作业证编号
        bean.setCode(entity.getCode());
        // 作业类型
        bean.setType(entity.getType());
        // 作业级别
        Integer workLevel = entity.getWorkLevel();
        bean.setWorkLevel(workLevel);
        bean.setWorkLevelName(WorkLevels.findNameById(workLevel));
        if ("动火".equals(entity.getType()) && entity.getWorkLevel() == 0) {
            bean.setWorkLevelName("特殊危险");
        }
        // 作业开始时间
        bean.setStartTime(entity.getStartTime());
        // 作业结束时间
        bean.setEndTime(entity.getEndTime());
        // 申请日期
        bean.setApplyTime(entity.getApplyTime());
        // 状态
        bean.setState(entity.getState());
        bean.setStateName(SafetyWorkStates.findNameById(entity.getState()));
        if (entity.getCheckState() == null || entity.getCheckState() == 0) {
            bean.setCheckStateName("待验收");

        } else if (entity.getCheckState() == 1) {
            bean.setCheckStateName("验收通过");
        }
        // 申请单位
        bean.setApplyDepartId(entity.getApplyDepartId());
        if (entity.getApplyDepartId() != null) {
            bean.setApplyDepartName(bpDepartDao.getOne(entity.getApplyDepartId()).getName());
        }
        // 申请人
        if (entity.getApplyUserId() != null) {
            bean.setApplyUserId(entity.getApplyUserId());
            if (entity.getApplyUserId() != null) {
                if (peopleTypeBean == null) {
                    bean.setApplyUserName(getName(baseUserDao.getBaseUserNameById(entity.getApplyUserId()), getCertNames(entity.getApplyUserCertIdJson())));

                } else if (peopleTypeBean.getApplyUserType() != null && peopleTypeBean.getApplyUserType() == 1) {
                    bean.setApplyUserName(getName(bpContractorStaffService.getNameById(entity.getApplyUserId()), getCertNames(entity.getApplyUserCertIdJson())));
                } else {
                    bean.setApplyUserName(getName(baseUserDao.getBaseUserNameById(entity.getApplyUserId()), getCertNames(entity.getApplyUserCertIdJson())));
                }
            }
        }

        // 作业地点
        if (StringUtils.isBlank(entity.getLocationCoords())) {
            bean.setLocationCoords("");
        } else {
            bean.setLocationCoords(entity.getLocationCoords());
        }
        // 作业内容
        bean.setWorkContent(entity.getWorkContent());
        // 所属风险区域
        if (entity.getRiskDistrictId() != null) {
            bean.setRiskDistrictId(entity.getRiskDistrictId());
            bean.setRiskDistrictName(riskDistrictDao.getOne(entity.getRiskDistrictId()).getName());
            // 查询风险点信息
            RiskPointControlRiskListSearchBean c = new RiskPointControlRiskListSearchBean();
            c.setRiskDistrictId(entity.getRiskDistrictId());
            Page<RiskPointInDistrictListBean> data = riskPointService
                    .findRiskPointsInDistrictPage(PageRequest.of(0, 1000), c);
            bean.setRiskPoints(ResultBean.pageData(data));
        } else {
            // 为了兼容前端，没有处理没有风险点的情况
            bean.setRiskPoints(ResultBean.pageData(new PageImpl<>(Collections.EMPTY_LIST)));
        }
        // 监护人
        bean.setMonitorUserCode(entity.getMonitorUserCode());
        // baseUserDao.findByCode(null)
        if (StringUtils.isNotBlank(entity.getMonitorUserCode())) {
            if (peopleTypeBean == null) {
                bean.setMonitorUserName(getName(findUserNameByCode(entity.getMonitorUserCode()), getCertNames(entity.getMonitorUserCertIdJson())));
            } else if (peopleTypeBean.getOpMonitorUserType() != null && peopleTypeBean.getOpMonitorUserType() == 1) {
                bean.setMonitorUserName(getName(bpContractorStaffService.getNameById(parseLong(entity.getMonitorUserCode())), getCertNames(entity.getMonitorUserCertIdJson())));
            } else {
                bean.setMonitorUserName(getName(findUserNameByCode(entity.getMonitorUserCode()), getCertNames(entity.getMonitorUserCertIdJson())));
            }
        }

        // 实施安全教育人
        if (StringUtils.isNotBlank(entity.getEducationUserCode())) {
            bean.setEducationUserCode(entity.getEducationUserCode());
            if (peopleTypeBean == null) {
                bean.setEducationUserName(getName(findUserNameByCode(entity.getEducationUserCode()), getCertNames(entity.getEducationUserCertIdJson())));
            } else if (peopleTypeBean.getOpEducationUserType() != null && peopleTypeBean.getOpEducationUserType() == 1) {
                bean.setEducationUserName(getName(bpContractorStaffService.getNameById(parseLong(entity.getEducationUserCode())), getCertNames(entity.getEducationUserCertIdJson())));
            } else {
                bean.setEducationUserName(getName(findUserNameByCode(entity.getEducationUserCode()), getCertNames(entity.getEducationUserCertIdJson())));
            }
        }

        // 风险点
        bean.setRiskPointId(entity.getRiskPointId());
        if (entity.getRiskPointId() != null) {
            bean.setRiskPointName(riskPointDao.getOne(entity.getRiskPointId()).getName());
        }
        // 风险级别
        bean.setRiskLevel(entity.getRiskLevel());
        if (entity.getRiskLevel() != null) {
            // EvalutionResult 和riskLevelName一个意思，只是为了兼容前端，后期可以考虑统一前后端字段命名，删除其中一个
            bean.setEvalutionResult(RiskLevels.findRiskLevelName(entity.getRiskLevel()));
        } else {
            if (entity.getRiskPointId() != null) {
                Integer riskLevel = riskPointDao.getOne(entity.getRiskPointId()).getRiskLevel();
                bean.setRiskLevel(riskLevel);
                // bean.setRiskLevelName(RiskLevels.findRiskLevelName(riskLevel));
                bean.setEvalutionResult(RiskLevels.findRiskLevelName(riskLevel));
            }
        }
        // 附件ID
        if (entity.getAttachmentId() != null) {
            bean.setAttachment(baseAttachmentRepositoryService.findByIdIntoBean(entity.getAttachmentId()));
        }
        //作业地点
        bean.setJobSite(entity.getJobSite());
        // 危害辨识
        bean.setDangerRecoganize(entity.getDangerRecoganize());
        // 编制人
        if (entity.getEditUserId() != null) {
            bean.setEditUserId(entity.getEditUserId());
            if (peopleTypeBean == null) {
                bean.setEditUserName(getName(baseUserDao.getBaseUserNameById(entity.getEditUserId()), getCertNames(entity.getEditUserCertIdJson())));
            } else if (peopleTypeBean.getEditUserType() != null && peopleTypeBean.getEditUserType() == 1) {
                bean.setEditUserName(getName(bpContractorStaffService.getNameById(entity.getEditUserId()), getCertNames(entity.getEditUserCertIdJson())));
            } else {
                bean.setEditUserName(getName(baseUserDao.getBaseUserNameById(entity.getEditUserId()), getCertNames(entity.getEditUserCertIdJson())));
            }
        }
        // 涉及的其他特殊作业
        if (StringUtils.isNotBlank(entity.getOtherSpecialWorkId())) {
            List<BpOtherSpecialWorkBean> bpOtherSpecialWorkBeans = new ArrayList<>();
            List<String> otherSpecialWorkName = new ArrayList<>();
            String otherSpecialJson = entity.getOtherSpecialWorkId();
            List<Long> oswList = formatOtherSpecial(otherSpecialJson);
            if (!org.springframework.util.CollectionUtils.isEmpty(oswList)) {
                for (Long osw : oswList) {
                    BpOtherSpecialWorkBean bpOtherSpecialWorkBean = new BpOtherSpecialWorkBean();
                    bpOtherSpecialWorkBean.setOtherSpecialWorkId(osw);
                    Optional<BpWorkSafetyCert> byId = dao.findById(osw);
                    if (byId.isPresent()) {
                        bpOtherSpecialWorkBean.setOtherSpecialWorkName(byId.get().getType() + "(" + byId.get().getCode() + ")");
                        otherSpecialWorkName.add(byId.get().getType() + "(" + byId.get().getCode() + ")");
                    }
                    bpOtherSpecialWorkBeans.add(bpOtherSpecialWorkBean);
                }
            }
            bean.setOtherSpecialWorkId(oswList);
            bean.setOtherSpecialWorkName(otherSpecialWorkName);
            bean.setBpOtherSpecialWorkBeans(bpOtherSpecialWorkBeans);
        }

        bean.setJhaEvaluationId(entity.getJhaEvaluationId());
        // 审核人
        bean.setAuditUserId(entity.getAuditUserId());
        bean.setAuditUserName(baseUserDao.getBaseUserNameById(entity.getAuditUserId()));
        bean.setNeedEletricityApplySheet(entity.getNeedEletricityApplySheet());
        bean.setWorkToolName(entity.getWorkToolName());
        // 审核时间
        if (entity.getAuditTime() != null) {
            bean.setAuditTime(SimpleDateFormatCache.getYmd().format(entity.getAuditTime()));
        }
        // 审核信息
        bean.setAuditMsg(entity.getAuditMsg());
        // 验收状态
        bean.setCheckState(entity.getCheckState());
        // 验收人
        bean.setCheckUserId(entity.getCheckUserId());
        bean.setCheckUser(baseUserDao.getBaseUserNameById(entity.getCheckUserId()));
        // 验收时间
        if (entity.getCheckTime() != null) {
            bean.setCheckTime(SimpleDateFormatCache.getYmd().format(entity.getCheckTime()));
        }
        // 验收备注
        bean.setCheckRemark(entity.getCheckRemark());
        // 设置人员信息
        List<BpWorkSafetyApplyUserDetailBean> tempList = queryPeopleInfo(entity);
        bean.setPeople(tempList);
        bean.setOperatorUserCertNames(tempList);
        bean.setSafetyMethods(querySafetyMethods(entity));
        //受限空间记录
        bean.setWebSpaceBeans(queryWebSpaceBean(entity));
        // 设置验收信息
        setCheckAndAuditInfo2(bean, entity);
        bean.setAlarm(entity.getAlarm());
        // 作业其他信息内容字段（JSON格式）
        // bean.setWorkOtherInfoEntityJson(entity.getWorkOtherInfoEntityJson());
        //公有信息填充
        setBeanDetail(entity, bean);
        //特有信息填充
        extractExtraInfo(bean, entity);
        return bean;
    }

    private void setCheckAndAuditInfo2(BpWorkSafetyCertDetailBean bean, BpWorkSafetyCert entity) {
        bean.setAuditState(entity.getState());
        bean.setAuditMsg(entity.getAuditMsg());
        if (entity.getAuditTime() != null) {
            bean.setAuditTime(SimpleDateFormatCache.getYmdhms().format(entity.getAuditTime()));
        }
        bean.setAuditUser(baseUserDao.getBaseUserNameById(entity.getAuditUserId()));
        bean.setCheckMsg(entity.getCheckRemark());
        bean.setCheckState(entity.getCheckState());
        if (entity.getCheckTime() != null) {
            bean.setCheckTime(SimpleDateFormatCache.getYmdhms().format(entity.getCheckTime()));
        }
        if (entity.getCheckUserId() != null) {
            bean.setCheckUser(baseUserDao.getBaseUserNameById(entity.getCheckUserId()));
        }

        //      bean.setCheckStateName(parseCheckStateName());

    }

    private BpWorkSafetyCertDetailBean createDetailBeanByType(BpWorkSafetyCert entity) {
        SafetyWorkTypes type = SafetyWorkTypes.findByName(entity.getType());
        if (type == SafetyWorkTypes.SHOU_XIAN_KONG_JIAN) {
            return new BpWorkSafetyCertRestrictedSpaceDetailBean();
        } else if (type == SafetyWorkTypes.GAO_CHU) {
            return new BpWorkSafetyCertHighDetailBean();
        } else if (type == SafetyWorkTypes.DIAO_ZHUANG) {
            return new BpWorkSafetyCertLiftingDetailBean();
        } else if (type == SafetyWorkTypes.LIN_SHI_YONG_DIAN) {
            return new BpWorkSafetyCertTempElectricityDetailBean();
        } else if (type == SafetyWorkTypes.MANG_BAN_CHOU_DU) {
            return new BpWorkSafetyCertBlindPlateDetailBean();
        } else if (type == SafetyWorkTypes.DUAN_LU) {
            return new BpWorkSafetyCertBreakRoadDetailBean();
        } else if (type == SafetyWorkTypes.DONG_TU) {
            return new BpWorkSafetyCertBreakGroundDetailBean();
        } else if (type == SafetyWorkTypes.DONG_HUO) {
            return new BpWorkSafetyApplyFireEditBean();
        } else if (type == SafetyWorkTypes.YI_BAN) {
            return new BpWorkSafetyCertYiBanDetailBean();
        }
        return null;
    }

    private void extractExtraInfo(BpWorkSafetyCertDetailBean bean, BpWorkSafetyCert entity) {
        BpWorkSafetyPeopleTypeBean peopleTypeBean = null;
        if (StringUtils.isNotBlank(entity.getPeopleTypeJson())) {
            peopleTypeBean = JSONObject.parseObject(entity.getPeopleTypeJson(), BpWorkSafetyPeopleTypeBean.class);
        }
        SafetyWorkTypes type = SafetyWorkTypes.findByName(entity.getType());
        if (type == SafetyWorkTypes.SHOU_XIAN_KONG_JIAN) {
            BpWorkSafetyCertRestrictedSpaceDetailBean detail = (BpWorkSafetyCertRestrictedSpaceDetailBean) bean;
            BpWorkSafetyCertRestrictedSpaceEditBean store = parse(BpWorkSafetyCertRestrictedSpaceEditBean.class,
                    entity.getWorkOtherInfoEntityJson());
            detail.setOpDepartResponsibleUserCode(store.getOpDepartResponsibleUserCode());
            if (StringUtils.isNotBlank(store.getOpDepartResponsibleUserCode())) {
                if (peopleTypeBean == null) {
                    detail.setOpDepartResponsibleUserName(getName(findUserNameByCode(store.getOpDepartResponsibleUserCode()), getCertNames(store.getOpDepartResponsibleUserCertIds())));
                } else if (peopleTypeBean.getOpDepartResponsibleUserType() != null && peopleTypeBean.getOpDepartResponsibleUserType() == 1) {
                    detail.setOpDepartResponsibleUserName(getName(bpContractorStaffService.getNameById(parseLong(store.getOpDepartResponsibleUserCode())), getCertNames(store.getOpDepartResponsibleUserCertIds())));
                } else {
                    detail.setOpDepartResponsibleUserName(getName(findUserNameByCode(store.getOpDepartResponsibleUserCode()), getCertNames(store.getOpDepartResponsibleUserCertIds())));
                }
            }

            detail.setOriginMediumNameInSpace(store.getOriginMediumNameInSpace());
            detail.setSpaceName(store.getSpaceName());
            if (store.getSapceDepartId() != null) {
                Optional<BpDepart> obd = bpDepartDao.findById(store.getSapceDepartId());
                if (obd.isPresent()) {
                    detail.setSapceDepartName(obd.get().getName());
                }
            }
            detail.setSapceDepartId(store.getSapceDepartId());
            detail.setOpDepartResponsibleUserCertNames(getBpWorkSafetyCertDtos(store.getOpDepartResponsibleUserCertIds()));
        } else if (type == SafetyWorkTypes.GAO_CHU) {
            BpWorkSafetyCertHighDetailBean detail = (BpWorkSafetyCertHighDetailBean) bean;
            BpWorkSafetyCertHighEditBean store = parse(BpWorkSafetyCertHighEditBean.class,
                    entity.getWorkOtherInfoEntityJson());
            detail.setWorkHeight(store.getWorkHeight());
            detail.setWorkDepartCode(store.getWorkDepartCode());
            if (StringUtils.isNoneBlank(store.getWorkDepartCode())) {
                detail.setWorkDepartName(bpDepartDao.getOne(Long.parseLong(store.getWorkDepartCode())).getName());
            }
        } else if (type == SafetyWorkTypes.DIAO_ZHUANG) {
            BpWorkSafetyCertLiftingDetailBean detail = (BpWorkSafetyCertLiftingDetailBean) bean;
            BpWorkSafetyCertLiftingEditBean store = parse(BpWorkSafetyCertLiftingEditBean.class,
                    entity.getWorkOtherInfoEntityJson());
            //吊装指挥人
            detail.setLiftingCommanderCertNo(store.getLiftingCommanderCertNo());
            detail.setLiftingCommanderCode(store.getLiftingCommanderCode());
            if (StringUtils.isNotBlank(store.getLiftingCommanderCode())) {
                if (peopleTypeBean == null) {
                    detail.setLiftingCommanderName(getName(findUserNameByCode(store.getLiftingCommanderCode()), getCertNames(store.getLiftingCommanderCodeCertIds())));
                } else if (peopleTypeBean.getLiftingCommanderType() != null && peopleTypeBean.getLiftingCommanderType() == 1) {
                    detail.setLiftingCommanderName(getName(bpContractorStaffService.getNameById(parseLong(store.getLiftingCommanderCode())), getCertNames(store.getLiftingCommanderCodeCertIds())));
                } else {
                    detail.setLiftingCommanderName(getName(findUserNameByCode(store.getLiftingCommanderCode()), getCertNames(store.getLiftingCommanderCodeCertIds())));
                }
            }

            //吊装人员
            detail.setLiftingOpUserCertNo(store.getLiftingOpUserCertNo());
            detail.setLiftingOpUserCode(store.getLiftingOpUserCode());
            if (StringUtils.isNotBlank(store.getLiftingOpUserCode())) {
                if (peopleTypeBean == null) {
                    detail.setLiftingOpUserName(getName(findUserNameByCode(store.getLiftingOpUserCode()), getCertNames(store.getLiftingOpUserCodeCertIds())));
                } else if (peopleTypeBean.getLiftingOpUserType() != null && peopleTypeBean.getLiftingOpUserType() == 1) {
                    detail.setLiftingOpUserName(getName(bpContractorStaffService.getNameById(parseLong(store.getLiftingOpUserCode())), getCertNames(store.getLiftingOpUserCodeCertIds())));
                } else {
                    detail.setLiftingOpUserName(getName(findUserNameByCode(store.getLiftingOpUserCode()), getCertNames(store.getLiftingOpUserCodeCertIds())));
                }
            }
            if (StringUtils.isNotBlank(store.getLiftingToolName())) {
                detail.setLiftingToolName(store.getLiftingToolName());
            } else {
                detail.setLiftingToolName(store.getWorkToolName());
            }
            detail.setWeight(store.getWeight());
            // 吊装人员证书
            detail.setLiftingOpUserCodeCertName(getBpWorkSafetyCertDtos(store.getLiftingOpUserCodeCertIds()));
            // 吊装指挥证书
            detail.setLiftingCommanderCodeCertName(getBpWorkSafetyCertDtos(store.getLiftingCommanderCodeCertIds()));
        } else if (type == SafetyWorkTypes.LIN_SHI_YONG_DIAN) {
            BpWorkSafetyCertTempElectricityDetailBean detail = (BpWorkSafetyCertTempElectricityDetailBean) bean;
            BpWorkSafetyCertTempElectricityEditBean store = parse(BpWorkSafetyCertTempElectricityEditBean.class,
                    entity.getWorkOtherInfoEntityJson());
            detail.setVoltage(store.getVoltage());
            detail.setDeviceAndPower(store.getDeviceAndPower());
            detail.setJoinInPoint(store.getJoinInPoint());
        } else if (type == SafetyWorkTypes.MANG_BAN_CHOU_DU) {
            BpWorkSafetyCertBlindPlateDetailBean detail = (BpWorkSafetyCertBlindPlateDetailBean) bean;
            BpWorkSafetyCertBlindPlateEditBean store = parse(BpWorkSafetyCertBlindPlateEditBean.class,
                    entity.getWorkOtherInfoEntityJson());
            // BeanUtils.copyProperties(store, detail, BpWorkSafetyCertBlindPlateEditBean.class);
            detail.setPipeName(store.getPipeName());
            // 介质
            detail.setMedium(store.getMedium());
            // 温度
            detail.setTemperature(store.getTemperature());
            // 压力
            detail.setPressure(store.getPressure());
            // 实施时间-堵
            detail.setOpTimeBlock(store.getOpTimeBlock());
            // 实施时间-抽
            detail.setOpTimePump(store.getOpTimePump());
            // 盲板-材质
            detail.setPlateMaterial(store.getPlateMaterial());
            // 盲板-规格
            detail.setPlateSpec(store.getPlateSpec());
            // 盲板-编号
            detail.setPlateCode(store.getPlateCode());

            // 监护人-堵
            detail.setBlockMonitorUserCode(store.getBlockMonitorUserCode());
            if (StringUtils.isNotBlank(store.getBlockMonitorUserCode())) {
                if (peopleTypeBean == null) {
                    detail.setBlockMonitorUserName(getName(findUserNameByCode(store.getBlockMonitorUserCode()), getCertNames(store.getBlockMonitorUserCodeCertIds())));
                } else if (peopleTypeBean.getBlockMonitorUserType() != null && peopleTypeBean.getBlockMonitorUserType() == 1) {
                    detail.setBlockMonitorUserName(getName(bpContractorStaffService.getNameById(parseLong(store.getBlockMonitorUserCode())), getCertNames(store.getBlockMonitorUserCodeCertIds())));
                } else {
                    detail.setBlockMonitorUserName(getName(findUserNameByCode(store.getBlockMonitorUserCode()), getCertNames(store.getBlockMonitorUserCodeCertIds())));
                }
            }

            // 监护人-抽
            detail.setPumpMonitorUserCode(store.getPumpMonitorUserCode());
            if (StringUtils.isNotBlank(store.getPumpMonitorUserCode())) {
                if (peopleTypeBean == null) {
                    detail.setPumpMonitorUserName(getName(findUserNameByCode(store.getPumpMonitorUserCode()), getCertNames(store.getPumpMonitorUserCodeCertIds())));
                } else if (peopleTypeBean.getPumpMonitorUserType() != null && peopleTypeBean.getPumpMonitorUserType() == 1) {
                    detail.setPumpMonitorUserName(getName(bpContractorStaffService.getNameById(parseLong(store.getPumpMonitorUserCode())), getCertNames(store.getPumpMonitorUserCodeCertIds())));
                } else {
                    detail.setPumpMonitorUserName(getName(findUserNameByCode(store.getPumpMonitorUserCode()), getCertNames(store.getPumpMonitorUserCodeCertIds())));
                }
            }

//            detail.setBlockMonitorUserName(findUserNameByCode(store.getBlockMonitorUserCode()));
//            detail.setPumpMonitorUserName(findUserNameByCode(store.getPumpMonitorUserCode()));
            // 生产单位作业指挥
            detail.setProductDepartCommanderCode(store.getProductDepartCommanderCode());
            if (StringUtils.isNotBlank(store.getProductDepartCommanderCode())) {
                if (peopleTypeBean == null) {
                    detail.setProductDepartCommanderName(getName(findUserNameByCode(store.getProductDepartCommanderCode()), getCertNames(store.getProductDepartCommanderCodeCertIds())));
                } else if (peopleTypeBean.getProductDepartCommanderType() != null && peopleTypeBean.getProductDepartCommanderType() == 1) {
                    detail.setProductDepartCommanderName(getName(bpContractorStaffService.getNameById(parseLong(store.getProductDepartCommanderCode())), getCertNames(store.getProductDepartCommanderCodeCertIds())));
                } else {
                    detail.setProductDepartCommanderName(getName(findUserNameByCode(store.getProductDepartCommanderCode()), getCertNames(store.getProductDepartCommanderCodeCertIds())));
                }
            }
            // 作业单位负责人
            detail.setOpDepartCommanderCode(store.getOpDepartCommanderCode());
            if (StringUtils.isNotBlank(store.getOpDepartCommanderCode())) {
                if (peopleTypeBean == null) {
                    detail.setOpDepartCommanderName(getName(findUserNameByCode(store.getOpDepartCommanderCode()), getCertNames(store.getOpDepartCommanderCodeCertIds())));
                } else if (peopleTypeBean.getOpDepartResponsibleUserType() != null && peopleTypeBean.getOpDepartResponsibleUserType() == 1) {
                    detail.setOpDepartCommanderName(getName(bpContractorStaffService.getNameById(parseLong(store.getOpDepartCommanderCode())), getCertNames(store.getOpDepartCommanderCodeCertIds())));
                } else {
                    detail.setOpDepartCommanderName(getName(findUserNameByCode(store.getOpDepartCommanderCode()), getCertNames(store.getOpDepartCommanderCodeCertIds())));
                }
            }
            //显示盲板抽堵人
            showMangBanChouDuPeople(detail, store);
            //监护人-堵 证书
            detail.setBlockMonitorUserCodeCertNames(getBpWorkSafetyCertDtos(store.getBlockMonitorUserCodeCertIds()));
            //作业单位负责人证书
            detail.setOpDepartCommanderCodeCertNames(getBpWorkSafetyCertDtos(store.getOpDepartCommanderCodeCertIds()));
            //生产单位作业指挥证书
            detail.setProductDepartCommanderCodeCertNames(getBpWorkSafetyCertDtos(store.getProductDepartCommanderCodeCertIds()));
            // 监护人-抽证书
            detail.setPumpMonitorUserCodeCertNames(getBpWorkSafetyCertDtos(store.getPumpMonitorUserCodeCertIds()));
        } else if (type == SafetyWorkTypes.DONG_TU) {
            BpWorkSafetyCertBreakGroundDetailBean detail = (BpWorkSafetyCertBreakGroundDetailBean) bean;
            BpWorkSafetyCertBreakGroundEditBean store = parse(BpWorkSafetyCertBreakGroundEditBean.class,
                    entity.getWorkOtherInfoEntityJson());
            detail.setContentImage(store.getContentImage());
            detail.setWorkDepartCode(store.getWorkDepartCode());
            if (StringUtils.isNotBlank(store.getWorkDepartCode())) {
                detail.setWorkDepartName(bpDepartDao.getOne(Long.parseLong(store.getWorkDepartCode())).getName());
            }
        } else if (type == SafetyWorkTypes.DUAN_LU) {
            BpWorkSafetyCertBreakRoadDetailBean detail = (BpWorkSafetyCertBreakRoadDetailBean) bean;
            BpWorkSafetyCertBreakRoadEditBean store = parse(BpWorkSafetyCertBreakRoadEditBean.class,
                    entity.getWorkOtherInfoEntityJson());
            detail.setBreakDescription(store.getBreakDescription());
            detail.setBreakReason(store.getBreakReason());
            detail.setImage(store.getImage());
            detail.setWorkDepartCode(store.getWorkDepartCode());
            detail.setOtherDepartId(store.getOtherDepartId());
            //作业单位负责人
            detail.setOpDepartResponsibleUserCode(store.getOpDepartResponsibleUserCode());
            if (StringUtils.isNotBlank(store.getOpDepartResponsibleUserCode())) {
                if (peopleTypeBean == null) {
                    detail.setOpDepartResponsibleUserName(getName(findUserNameByCode(store.getOpDepartResponsibleUserCode()), getCertNames(store.getOpDepartResponsibleUserCertIds())));
                } else if (peopleTypeBean.getOpDepartResponsibleUserType() != null && peopleTypeBean.getOpDepartResponsibleUserType() == 1) {
                    detail.setOpDepartResponsibleUserName(getName(bpContractorStaffService.getNameById(parseLong(store.getOpDepartResponsibleUserCode())), getCertNames(store.getOpDepartResponsibleUserCertIds())));
                } else {
                    detail.setOpDepartResponsibleUserName(getName(findUserNameByCode(store.getOpDepartResponsibleUserCode()), getCertNames(store.getOpDepartResponsibleUserCertIds())));
                }
            }
            if (store.getOtherDepartId() != null) {
                Optional<BpDepart> obd = bpDepartDao.findById(store.getOtherDepartId());
                if (obd.isPresent()) {
                    detail.setOtherDepartName(obd.get().getName());
                }
            }
            if (StringUtils.isNotBlank(store.getWorkDepartCode())) {
                // TODO 待修正，根据code获取单位编号
                detail.setWorkDepartName(bpDepartDao.getOne(Long.parseLong(store.getWorkDepartCode())).getName());
            }
        } else if (type == SafetyWorkTypes.YI_BAN) {
            BpWorkSafetyCertYiBanDetailBean detail = (BpWorkSafetyCertYiBanDetailBean) bean;
            BpWorkSafetyCertYiBanEditBean store = parse(BpWorkSafetyCertYiBanEditBean.class,
                    entity.getWorkOtherInfoEntityJson());
            // 设备位号
            detail.setDeviceNo(store.getDeviceNo());
            // 辖区单位
            detail.setDistrictDepart(store.getDistrictDepart());
            // 施工单位主管
            detail.setWorkDepartManagerId(store.getWorkDepartManagerId());
            if (peopleTypeBean == null) {
                detail.setWorkDepartManagerName(baseUserDao.getBaseUserNameById(store.getWorkDepartManagerId()));
            } else if (peopleTypeBean.getWorkDepartManagerType() != null && peopleTypeBean.getWorkDepartManagerType() == 1) {
                detail.setWorkDepartManagerName(bpContractorStaffService.getNameById(store.getWorkDepartManagerId()));
            } else {
                detail.setWorkDepartManagerName(baseUserDao.getBaseUserNameById(store.getWorkDepartManagerId()));
            }
            // 作业类别
            detail.setJobType(store.getJobType());
            detail.setJobTypeName(parseJobTypeName(store.getJobType()));
            // 勾选其他后填写的内容
            detail.setOtherTypeContent(store.getOtherTypeContent());
            // 辖区单位安全交出人
            detail.setDistrictDepartSafetySender(store.getDistrictDepartSafetySender());
            // 施工管理单位接收人
            detail.setInchargeManageDepartReceiver(store.getInchargeManageDepartReceiver());
            // 辖区单位主管
            detail.setDistrictDepartManager(store.getDistrictDepartManager());
            // 作业风险评估人
            detail.setJobRiskEvaluateUser(store.getJobRiskEvaluateUser());

            // 施工单位主管证书
            detail.setWorkDepartManagerCertName(getBpWorkSafetyCertDtos(store.getWorkDepartManagerCertIds()));
            // 辖区单位安全交出人证书
            detail.setDistrictDepartSafetySenderCertName(getBpWorkSafetyCertDtos(store.getDistrictDepartSafetySenderCertIds()));
            // 施工管理单位接收人证书
            detail.setInchargeManageDepartReceiverCertName(getBpWorkSafetyCertDtos(store.getInchargeManageDepartReceiverCertIds()));
        }
    }

    //显示盲板抽堵作业人和监护人信息
    private void showMangBanChouDuPeople(BpWorkSafetyCertBlindPlateDetailBean detail, BpWorkSafetyCertBlindPlateEditBean store) {
        List<BpWorkSafetyCertBlindPlatePeopleBean> peopleBeans = store.getPeopleBeans();
        List<BpWorkSafetyCertBlindPlatePeopleBean> pBeans = new ArrayList();
        if (!CollectionUtils.isEmpty(peopleBeans)) {
            for (BpWorkSafetyCertBlindPlatePeopleBean pb : peopleBeans) {
                BpWorkSafetyCertBlindPlatePeopleBean pBean = new BpWorkSafetyCertBlindPlatePeopleBean();
                //类型
                pBean.setType(pb.getType());
                pBean.setPeopleId(pb.getPeopleId());
                pBean.setGuardianId(pb.getGuardianId());
                pBean.setGuardianType(pb.getGuardianType());
                pBean.setPeopleType(pb.getPeopleType());
//                //实施时间
//                pBean.setEffectiveDate(pb.getEffectiveDate());
                //作业人和监护人姓名
                if (pb.getPeopleId() != null) {
                    if (pb.getPeopleType() != null && pb.getPeopleType() == 1) {
                        pBean.setPeopleName(bpContractorStaffService.getNameById(pb.getPeopleId()));
                    } else {
                        Optional<BaseUser> pbu = baseUserDao.findById(pb.getPeopleId());
                        if (pbu.isPresent()) {
                            pBean.setPeopleName(pbu.get().getRealName());
                        }
                    }
                }
                if (pb.getGuardianId() != null) {
                    if (pb.getGuardianType() != null && pb.getGuardianType() == 1) {
                        pBean.setGuardianName(bpContractorStaffService.getNameById(pb.getGuardianId()));
                    } else {
                        Optional<BaseUser> gbu = baseUserDao.findById(pb.getGuardianId());
                        if (gbu.isPresent()) {
                            pBean.setGuardianName(gbu.get().getRealName());
                        }
                    }
                }

                //获取证书名称
                //获取监护人证书名称
                List<OperatorCertAddDto> guardianDtos = pb.getGuardianDto();
                if (!CollectionUtils.isEmpty(guardianDtos)) {
                    List<OperatorCertAddDto> gList = new ArrayList();
                    for (OperatorCertAddDto gd : guardianDtos) {
                        OperatorCertAddDto gDto = new OperatorCertAddDto();
                        if (pb.getGuardianType() != null && pb.getGuardianType() == 1 && pb.getGuardianId() != null) {
                            EduCertificateUser eUser = eduCertificateUserDao.findByUserId(pb.getGuardianId());
                            if (eUser != null && eUser.getCertId() != null) {
                                gDto.setId(eUser.getCertId());
                                gDto.setName(eduCertificateDao.getNameById(eUser.getCertId()) + "(" + eduCertificateDao.getCodeById(eUser.getCertId()) + ")");
                            }
                        } else {
                            Optional<EduCertificate> og = eduCertificateDao.findById(gd.getId());
                            if (og.isPresent()) {
                                gDto.setId(og.get().getId());
                                gDto.setName(og.get().getName() + "(" + og.get().getCode() + ")");
                            }
                        }

                        gList.add(gDto);
                    }
                    pBean.setGuardianDto(gList);
                } else {
                    pBean.setGuardianDto(new ArrayList<>());
                }

                //获取作业人证书名称
                List<OperatorCertAddDto> peopleDtos = pb.getPeopleDto();
                if (!CollectionUtils.isEmpty(peopleDtos)) {
                    List<OperatorCertAddDto> pList = new ArrayList();
                    for (OperatorCertAddDto pd : peopleDtos) {
                        OperatorCertAddDto pDto = new OperatorCertAddDto();
                        if (pb.getPeopleType() != null && pb.getPeopleType() == 1 && pb.getPeopleId() != null) {
                            EduCertificateUser eUser = eduCertificateUserDao.findByUserId(pb.getPeopleId());
                            if (eUser != null && eUser.getCertId() != null) {
                                pDto.setId(eUser.getCertId());
                                pDto.setName(eduCertificateDao.getNameById(eUser.getCertId()) + "(" + eduCertificateDao.getCodeById(eUser.getCertId()) + ")");
                            }
                        } else {
                            Optional<EduCertificate> pg = eduCertificateDao.findById(pd.getId());
                            if (pg.isPresent()) {
                                pDto.setId(pg.get().getId());
                                pDto.setName(pg.get().getName() + "(" + pg.get().getCode() + ")");
                            }
                        }

                        pList.add(pDto);
                    }
                    pBean.setPeopleDto(pList);
                } else {
                    pBean.setPeopleDto(new ArrayList<>());
                }

                pBeans.add(pBean);
            }
        }
        detail.setPeopleBeans(pBeans);
    }

    //获取证书id+name(code)
    private List<BpWorkSafetyCertDto> getBpWorkSafetyCertDtos(List<Long> certIds) {
        List<BpWorkSafetyCertDto> resultCertName = Lists.newArrayList();
        if (certIds != null) {
            for (Long codeCertId : certIds) {
                String name = eduCertificateDao.getNameById(codeCertId);
                String code = eduCertificateDao.getCodeById(codeCertId);
                resultCertName.add(new BpWorkSafetyCertDto(codeCertId, name + "(" + code + ")"));
            }
        }
        return resultCertName;
    }

    private <T> T parse(Class<T> clazz, String json) {
        Gson gson = new Gson();
        T obj = gson.fromJson(json, clazz);
        try {
            return obj == null ? clazz.newInstance() : obj;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Page<BpWorkSafetyApplyFireListBean> findByPageFire(Pageable page, BpWorkSafetyCertSearchBean condition) {
        page = PageDataUtils.addOrderByDesc(page, "code");
        Predicate predicate = prepareListSearchCondition(condition, SafetyWorkTypes.DONG_HUO);
        Page<BpWorkSafetyCert> data = predicate == null ? dao.findAll(page) : dao.findAll(predicate, page);
        // Page<BpWorkSafetyCert> data = dao.findByType(SafetyWorkTypes.DONG_HUO.getName(), page);
        return PageDataUtils.convertPageData(data,
                new PageDataConvert<BpWorkSafetyApplyFireListBean, BpWorkSafetyCert>() {

                    @Override
                    public BpWorkSafetyApplyFireListBean convert(BpWorkSafetyCert f) {
                        BpWorkSafetyApplyFireListBean bean = new BpWorkSafetyApplyFireListBean();
                        // ID
                        bean.setId(f.getId());
                        // 作业证编号
                        bean.setCode(f.getCode());
                        // 作业类型
                        bean.setType(f.getType());
                        // 作业级别
                        bean.setWorkLevel(f.getWorkLevel());
                        bean.setWorkLevelName(WorkLevels.findNameById(f.getWorkLevel()));
                        if ("动火".equals(f.getType()) && f.getWorkLevel() == 0) {
                            bean.setWorkLevelName("特殊危险");
                        }
                        // 状态
                        bean.setState(f.getState());
                        bean.setStateName(SafetyWorkStates.findNameById(f.getState()));

                        // 所属风险区域
                        bean.setRiskDistrictId(f.getRiskDistrictId());
                        bean.setRiskDistrictName(riskDistrictDao.findNameById(f.getRiskDistrictId()));
                        //jha评估ID
                        bean.setJhaEvaluationId(f.getJhaEvaluationId());
                        // 工作内容
                        bean.setWorkContent(f.getWorkContent());
                        // 工作时间
                        bean.setWorkTime(parseWorkTime(f));
                        // 申请时间
                        bean.setApplyTime(SimpleDateFormatCache.getYmdZC().format(f.getApplyTime()));
                        if (f.getState() != null && f.getState() == 3) {
                            // 审核失败
                            bean.setAuditMsg(f.getAuditMsg());
                            if (f.getAuditUserId() != null) {
                                bean.setAuditUser(baseUserDao.getBaseUserNameById(f.getAuditUserId()));
                            }
                        }
                        return bean;
                    }
                });
    }

    // 查询
    @Override
    public BpWorkSafetyApplyFireEditBean findDetailByIdFire(Long id) {
        BpWorkSafetyApplyFireEditBean bean = new BpWorkSafetyApplyFireEditBean();
        BpWorkSafetyCert entity = dao.getOne(id);
        bean.setId(entity.getId());
        bean.setApplyTime(entity.getApplyTime());
        bean.setApplyDepartId(entity.getApplyDepartId());
        bean.setApplyDepartName(getDepartname(entity.getApplyDepartId()));
        BpWorkSafetyPeopleTypeBean peopleTypeBean = null;
        if (StringUtils.isNotBlank(entity.getPeopleTypeJson())) {
            peopleTypeBean = JSONObject.parseObject(entity.getPeopleTypeJson(), BpWorkSafetyPeopleTypeBean.class);
        }
        //人员分类
        bean.setPeopleTypeBean(peopleTypeBean);
        //申请人
        if (entity.getApplyUserId() != null) {
            if (peopleTypeBean == null) {
                bean.setApplyUserName(getName(baseUserDao.getBaseUserNameById(entity.getApplyUserId()), getCertNames(entity.getApplyUserCertIdJson())));
            } else if (peopleTypeBean.getApplyUserType() != null && peopleTypeBean.getApplyUserType() == 1) {
                bean.setApplyUserName(getName(bpContractorStaffService.getNameById(entity.getApplyUserId()), getCertNames(entity.getApplyUserCertIdJson())));
            } else {
                bean.setApplyUserName(getName(baseUserDao.getBaseUserNameById(entity.getApplyUserId()), getCertNames(entity.getApplyUserCertIdJson())));
            }
        }

        bean.setState(entity.getState());
        bean.setStateName(SafetyWorkStates.findNameById(entity.getState()));
        if (entity.getCheckState() == null || entity.getCheckState() == 0) {
            bean.setCheckStateName("待验收");
        } else if (entity.getCheckState() == 1) {
            bean.setCheckStateName("验收通过");
        }
        bean.setApplyUserId(entity.getApplyUserId());
        if (entity.getAttachmentId() != null) {
            bean.setAttachment(attachmentRepositoryService.findByIdIntoBean(entity.getAttachmentId()));
        }
        //工作地点
        bean.setJobSite(entity.getJobSite());
        bean.setCode(entity.getCode());
        bean.setDangerRecoganize(entity.getDangerRecoganize());
        //编制人
        bean.setEditUserId(entity.getEditUserId());
        if (entity.getEditUserId() != null) {
            if (peopleTypeBean == null) {
                bean.setEditUserName(getName(baseUserDao.getBaseUserNameById(entity.getEditUserId()), getCertNames(entity.getEditUserCertIdJson())));
            } else if (peopleTypeBean.getEditUserType() != null && peopleTypeBean.getEditUserType() == 1) {
                bean.setEditUserName(getName(bpContractorStaffService.getNameById(entity.getEditUserId()), getCertNames(entity.getEditUserCertIdJson())));
            } else {
                bean.setEditUserName(getName(baseUserDao.getBaseUserNameById(entity.getEditUserId()), getCertNames(entity.getEditUserCertIdJson())));
            }
        }

        // 涉及的其他特殊行业
        if (StringUtils.isNotBlank(entity.getOtherSpecialWorkId())) {
            List<BpOtherSpecialWorkBean> bpOtherSpecialWorkBeans = new ArrayList<>();
            List<String> otherSpecialWorkName = new ArrayList<>();
            String otherSpecialJson = entity.getOtherSpecialWorkId();
            List<Long> oswList = formatOtherSpecial(otherSpecialJson);
            if (!org.springframework.util.CollectionUtils.isEmpty(oswList)) {
                for (Long osw : oswList) {
                    BpOtherSpecialWorkBean bpOtherSpecialWorkBean = new BpOtherSpecialWorkBean();
                    bpOtherSpecialWorkBean.setOtherSpecialWorkId(osw);
                    Optional<BpWorkSafetyCert> byId = dao.findById(osw);
                    if (byId.isPresent()) {
                        bpOtherSpecialWorkBean.setOtherSpecialWorkName(byId.get().getType() + "(" + byId.get().getCode() + ")");
                        otherSpecialWorkName.add(byId.get().getType() + "(" + byId.get().getCode() + ")");
                    }
                    bpOtherSpecialWorkBeans.add(bpOtherSpecialWorkBean);
                }
            }
            bean.setBpOtherSpecialWorkBeans(bpOtherSpecialWorkBeans);
            bean.setOtherSpecialWorkName(otherSpecialWorkName);
            bean.setOtherSpecialWorkId(oswList);
        }

        bean.setEndTime(entity.getEndTime());
        bean.setStartTime(entity.getStartTime());
        if (StringUtils.isBlank(entity.getLocationCoords())) {
            bean.setLocationCoords("");
        } else {
            bean.setLocationCoords(entity.getLocationCoords());
        }
        bean.setOpFireContent(entity.getWorkContent());
        //实施安全教育人
        if (StringUtils.isNotBlank(entity.getEducationUserCode())) {
            if (peopleTypeBean == null) {
                bean.setOpFireEducationUserName(getName(findUserNameByCode(entity.getEducationUserCode()), getCertNames(entity.getEducationUserCertIdJson())));
            } else if (peopleTypeBean.getOpEducationUserType() != null && peopleTypeBean.getOpEducationUserType() == 1) {
                bean.setOpFireEducationUserName(getName(bpContractorStaffService.getNameById(Long.parseLong(entity.getEducationUserCode())), getCertNames(entity.getEducationUserCertIdJson())));
            } else {
                bean.setOpFireEducationUserName(getName(findUserNameByCode(entity.getEducationUserCode()), getCertNames(entity.getEducationUserCertIdJson())));
            }
        }
        bean.setOpFireEducationUserId(parseLong(entity.getEducationUserCode()));

        String json = entity.getWorkOtherInfoEntityJson();
        //动火特有字段
        BpWorkSafetyCertFireEditBean fb = null;
        if (StringUtils.isNotBlank(json)) {
            fb = formatFireMethod(json);
        }
        //动火特有字段(证书)
        BpWorkSafetyApplyFireAddBean addBean = new BpWorkSafetyApplyFireAddBean();
        if (entity.getWorkOtherUserCertIdJson() != null) {
            addBean = JSONObject.parseObject(entity.getWorkOtherUserCertIdJson(),
                    BpWorkSafetyApplyFireAddBean.class);
            // 生产单位负责人
            if (addBean.getProductionDepartResponsibleUserCertIds() != null && addBean.getProductionDepartResponsibleUserCertIds().size() > 0) {
                bean.setProductionDepartResponsibleUserCertName(getBpWorkSafetyCertDtos(addBean.getProductionDepartResponsibleUserCertIds()));
            }
            // 动火作业负责人
            if (addBean.getOpFireJobResponsibleUserCertIds() != null && addBean.getOpFireJobResponsibleUserCertIds().size() > 0) {
                bean.setOpFireJobResponsibleUserCertName(getBpWorkSafetyCertDtos(addBean.getOpFireJobResponsibleUserCertIds()));
            }

            // 动火初审人
            if (addBean.getOpFireFirstAuditUserCertIds() != null && addBean.getOpFireFirstAuditUserCertIds().size() > 0) {
                bean.setOpFireFirstAuditUserCertName(getBpWorkSafetyCertDtos(addBean.getOpFireFirstAuditUserCertIds()));
            }

            // 监火人
            if (addBean.getOpFireMonitorUserCertIds() != null && addBean.getOpFireMonitorUserCertIds().size() > 0) {
                bean.setOpFireMonitorUserCertName(getBpWorkSafetyCertDtos(addBean.getOpFireMonitorUserCertIds()));
            }

            // 实施安全教育人
            if (bean.getEducationUserCertName() != null && bean.getEducationUserCertName().getCertNames() != null) {
                bean.setOpFireEducationUserCertName(getBpWorkSafetyCertDtos(addBean.getOpFireEducationUserCertIds()));
            }
        }

        //动火人名
        if (fb != null) {
            //动火初审人
            if (StringUtils.isNotBlank(fb.getOpFireFirstAuditUserId())) {
                if (peopleTypeBean == null) {
                    bean.setOpFireFirstAuditUserName(getName(baseUserDao.getBaseUserNameById(parseLong(fb.getOpFireFirstAuditUserId())), getCertNames(addBean.getOpFireFirstAuditUserCertIds())));
                } else if (peopleTypeBean.getOpFireFirstAuditUserType() != null && peopleTypeBean.getOpFireFirstAuditUserType() == 1) {
                    bean.setOpFireFirstAuditUserName(getName(bpContractorStaffService.getNameById(parseLong(fb.getOpFireFirstAuditUserId())), getCertNames(addBean.getOpFireFirstAuditUserCertIds())));
                } else {
                    bean.setOpFireFirstAuditUserName(getName(baseUserDao.getBaseUserNameById(parseLong(fb.getOpFireFirstAuditUserId())), getCertNames(addBean.getOpFireFirstAuditUserCertIds())));
                }
                bean.setOpFireFirstAuditUserId(parseLong(fb.getOpFireFirstAuditUserId()));
            }


            //动火作业负责人
            if (StringUtils.isNotBlank(fb.getOpFireJobResponsibleUserId())) {
                if (peopleTypeBean == null) {
                    bean.setOpFireJobResponsibleUserName(getName(baseUserDao.getBaseUserNameById(parseLong(fb.getOpFireJobResponsibleUserId())), getCertNames(addBean.getOpFireJobResponsibleUserCertIds())));
                } else if (peopleTypeBean.getOpFireJobResponsibleUserType() != null && peopleTypeBean.getOpFireJobResponsibleUserType() == 1) {
                    bean.setOpFireJobResponsibleUserName(getName(bpContractorStaffService.getNameById(parseLong(fb.getOpFireJobResponsibleUserId())), getCertNames(addBean.getOpFireJobResponsibleUserCertIds())));
                } else {
                    bean.setOpFireJobResponsibleUserName(getName(baseUserDao.getBaseUserNameById(parseLong(fb.getOpFireJobResponsibleUserId())), getCertNames(addBean.getOpFireJobResponsibleUserCertIds())));
                }
                bean.setOpFireJobResponsibleUserId(parseLong(fb.getOpFireJobResponsibleUserId()));
            }

            //动火方式
            if (!CollectionUtils.isEmpty(fb.getOpFireMethodId())) {
                List<BpOpFireMethodBean> opFireMethodBeans = new ArrayList<>();
                for (Long ofm : fb.getOpFireMethodId()) {
                    BpOpFireMethodBean bpOpFireMethodBean = new BpOpFireMethodBean();
                    bpOpFireMethodBean.setOpFireMethodId(ofm);
                    bpOpFireMethodBean.setOpFireMethodName(baseTypeGroupItemDao.findNameById(ofm));
                    opFireMethodBeans.add(bpOpFireMethodBean);
                }
                bean.setOpFireMethodBeans(opFireMethodBeans);
                bean.setOpFireMethodId(fb.getOpFireMethodId());
            }

            //监火人
            if (StringUtils.isNotBlank(fb.getOpFireMonitorUserId())) {
                bean.setOpFireMonitorUserId(parseLong(fb.getOpFireMonitorUserId()));
                if (peopleTypeBean == null) {
                    bean.setOpFireMonitorUserName(getName(baseUserDao.getBaseUserNameById(parseLong(fb.getOpFireMonitorUserId())), getCertNames(addBean.getOpFireMonitorUserCertIds())));
                } else if (peopleTypeBean.getOpMonitorUserType() != null && peopleTypeBean.getOpMonitorUserType() == 1) {
                    bean.setOpFireMonitorUserName(getName(bpContractorStaffService.getNameById(parseLong(fb.getOpFireMonitorUserId())), getCertNames(addBean.getOpFireMonitorUserCertIds())));
                } else {
                    bean.setOpFireMonitorUserName(getName(baseUserDao.getBaseUserNameById(parseLong(fb.getOpFireMonitorUserId())), getCertNames(addBean.getOpFireMonitorUserCertIds())));
                }
            }


            // 生产责任人
            if (StringUtils.isNotBlank(fb.getProductionDepartResponsibleUserId())) {
                if (peopleTypeBean == null) {
                    bean.setProductionDepartResponsibleUserName(getName(baseUserDao.getBaseUserNameById(parseLong(fb.getProductionDepartResponsibleUserId())),
                            getCertNames(addBean.getProductionDepartResponsibleUserCertIds())));

                } else if (peopleTypeBean.getProductionDepartResponsibleUserType() != null && peopleTypeBean.getProductionDepartResponsibleUserType() == 1) {
                    bean.setProductionDepartResponsibleUserName(getName(bpContractorStaffService.getNameById(parseLong(fb.getProductionDepartResponsibleUserId())),
                            getCertNames(addBean.getProductionDepartResponsibleUserCertIds())));

                } else {
                    bean.setProductionDepartResponsibleUserName(getName(baseUserDao.getBaseUserNameById(parseLong(fb.getProductionDepartResponsibleUserId())),
                            getCertNames(addBean.getProductionDepartResponsibleUserCertIds())));

                }
                bean.setProductionDepartResponsibleUserId(parseLong(fb.getProductionDepartResponsibleUserId()));
            }
        }

        if (entity.getRiskDistrictId() != null) {
            // 风险区域
            bean.setRiskDistrictId(entity.getRiskDistrictId());
            bean.setRiskDistrictName(riskDistrictDao.getOne(entity.getRiskDistrictId()).getName());
            // 查询风险点信息
            RiskPointControlRiskListSearchBean c = new RiskPointControlRiskListSearchBean();
            c.setRiskDistrictId(entity.getRiskDistrictId());
            Page<RiskPointInDistrictListBean> data = riskPointService
                    .findRiskPointsInDistrictPage(PageRequest.of(0, 1000), c);
            bean.setRiskPoints(ResultBean.pageData(data));
        } else {
            // 为了兼容前端，没有处理没有风险点的情况
            bean.setRiskPoints(ResultBean.pageData(new PageImpl<>(Collections.EMPTY_LIST)));
        }

        bean.setRiskPointId(entity.getRiskPointId());
        if (entity.getRiskPointId() != null) {
            bean.setRiskPointName(riskPointDao.findNameById(entity.getRiskPointId()));
        }

        bean.setJhaEvaluationId(entity.getJhaEvaluationId());

        bean.setWorkLevel(entity.getWorkLevel());
        bean.setWorkLevelName(WorkLevels.findNameById(entity.getWorkLevel()));
        if ("动火".equals(entity.getType()) && entity.getWorkLevel() == 0) {
            bean.setWorkLevelName("特殊危险");
        }
        bean.setType(entity.getType());
        bean.setRiskLevel(entity.getRiskLevel());
        bean.setRiskLevelName(RiskLevels.findRiskLevelName(entity.getRiskLevel()));

        if (entity.getRiskLevel() != null) {
            // EvalutionResult 和riskLevelName一个意思，只是为了兼容前端，后期可以考虑统一前后端字段命名，删除其中一个
            bean.setEvalutionResult(bean.getRiskLevelName());
        } else {
            if (entity.getRiskPointId() != null) {
                Optional<RiskDistrict> osd = riskDistrictDao.findById(entity.getRiskPointId());
                if (osd.isPresent()) {
                    bean.setRiskLevel(osd.get().getRiskLevel());
                    if (osd.get().getRiskLevel() != null) {
                        bean.setRiskLevelName(RiskLevels.findRiskLevelName(osd.get().getRiskLevel()));
                        bean.setEvalutionResult(bean.getRiskLevelName());
                    }
                }
//                Integer riskLevel = riskPointDao.getOne(entity.getRiskPointId()).getRiskLevel();
//                bean.setRiskLevel(riskLevel);
//                bean.setRiskLevelName(RiskLevels.findRiskLevelName(riskLevel));
//                bean.setEvalutionResult(bean.getRiskLevelName());
            }
        }

        // 设置报警
        bean.setAlarm(entity.getAlarm());
        // 2019-12-13添加
        bean.setNeedEletricityApplySheet(entity.getNeedEletricityApplySheet());
        bean.setWorkToolName(entity.getWorkToolName());
        List<BpWorkSafetyApplyUserDetailBean> tempList = queryPeopleInfo(entity);
        bean.setPeople(tempList);
        bean.setOperatorUserCertNames(tempList);
        //安全措施
        bean.setSafetyMethods(querySafetyMethods(entity));
        //动火分析记录
        bean.setWebFileBeans(queryWebFileBeam(entity));
        // 设置验收信息
        setCheckAndAuditInfo(bean, entity);

        //公有字段
        setBeanDetail(entity, bean);
        return bean;
    }

    // 处理动火作业方式只有一个的问题(旧数据兼容)
    private BpWorkSafetyCertFireEditBean formatFireMethod(String json) {
        BpWorkSafetyCertFireEditBean fb = null;
        JSONObject jsonObj = JSONObject.parseObject(json);
        Object opFireMethod = jsonObj.get("opFireMethodId");
        if (opFireMethod != null && opFireMethod instanceof Integer) {
            List<Long> list = new ArrayList<>();
            if (opFireMethod != null) {
                list.add(Long.valueOf(opFireMethod.toString()));
            }
            jsonObj.put("opFireMethodId", list);
            json = jsonObj.toJSONString();
        }
        fb = new Gson().fromJson(json, BpWorkSafetyCertFireEditBean.class);

        return fb;
    }

    // 处理其他特殊作业只有一个的问题(旧数据兼容)
    private List<Long> formatOtherSpecial(String json) {
        List<Long> list = null;
        if (!json.contains("[")) {
            json = "[" + json + "]";
        }
        list = JSONObject.parseArray(json, Long.class);
        return list;
    }

    private String getName(String name, List<String> list) {
        if (!CollectionUtils.isEmpty(list)) {
            return name + "(" + Joiner.on(",").join(list) + ")";
        } else {
            return name;
        }
    }

    private List<String> getCertNames(List<Long> alist) {
        List<String> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(alist)) {
            for (Long certId : alist) {
                String name = eduCertificateDao.getNameById(certId);
                String code = eduCertificateDao.getCodeById(certId);
                list.add(name + "(" + code + ")");
            }

        }
        return list;
    }

    private List<String> getCertNames(String json) {
        List<String> list = new ArrayList<>();
        if (StringUtils.isNotBlank(json)) {
            List<BpWorkSafetyCertDto> certNameList = getCertNameList(json);
            if (!CollectionUtils.isEmpty(certNameList)) {
                for (BpWorkSafetyCertDto certDto : certNameList) {
                    String name = eduCertificateDao.getNameById(certDto.getCertId());
                    String code = eduCertificateDao.getCodeById(certDto.getCertId());
                    list.add(name + "(" + code + ")");
                }
            }
        }
        return list;
    }

    private void setBeanDetail(BpWorkSafetyCert entity, BpWorkSafetyCertDetailBean bean) {
        //申请人证书ids
        String applyUserCertIdJson = entity.getApplyUserCertIdJson();
        System.out.println("+++++++++{" + applyUserCertIdJson);
        if (applyUserCertIdJson != null) {
            List<BpWorkSafetyCertDto> certNameList = getCertNameList(applyUserCertIdJson);
            bean.setApplyUserCertName(new BpWorkUserCertsDto(bean.getApplyUserName(), certNameList));
        }
        //监护人证书ids
        String monitorUserCertIdJson = entity.getMonitorUserCertIdJson();
        if (monitorUserCertIdJson != null) {
            List<BpWorkSafetyCertDto> certNameList1 = getCertNameList(monitorUserCertIdJson);
            bean.setMonitorUserCertName(new BpWorkUserCertsDto(bean.getMonitorUserName(), certNameList1));
        }
        //实施安全教育人证书ids
        String educationUserCertIdJson = entity.getEducationUserCertIdJson();
        if (educationUserCertIdJson != null) {
            List<BpWorkSafetyCertDto> certNameList2 = getCertNameList(educationUserCertIdJson);
            bean.setEducationUserCertName(new BpWorkUserCertsDto(bean.getEducationUserName(), certNameList2));
        }
        //编制人证书ids
        String editUserCertIdJson = entity.getEditUserCertIdJson();
        if (editUserCertIdJson != null) {
            List<BpWorkSafetyCertDto> certNameList3 = getCertNameList(editUserCertIdJson);
            bean.setEditUserCertName(new BpWorkUserCertsDto(bean.getEditUserName(), certNameList3));
        }
    }

    private List<BpWorkSafetyCertDto> getCertNameList(String userCertIdJson) {
        List<BpWorkSafetyCertDto> certNameList = Lists.newArrayList();
        List<Long> userCertIds = JSON.parseArray(userCertIdJson, Long.class);
        if (userCertIds != null) {
            for (Long uerCertId : userCertIds) {
                certNameList.add(new BpWorkSafetyCertDto(uerCertId, eduCertificateDao.getNameById(uerCertId)));
            }
        }
        return certNameList;
    }

    private Long parseLong(String code) {
        if (StringUtils.isBlank(code)) {
            return null;
        }
        try {
            return Long.parseLong(code);
        } catch (Exception e) {
        }
        return null;
    }

    private String findUserNameByCode(String educationUserCode) {
        if (StringUtils.isBlank(educationUserCode)) {
            return null;
        }
        // TODO 修复按code查找用户名的方法
        return baseUserDao.getBaseUserNameById(Long.parseLong(educationUserCode));
    }

    private void setCheckAndAuditInfo(BpWorkSafetyApplyFireEditBean bean, BpWorkSafetyCert entity) {
        bean.setAuditState(entity.getState());
        bean.setAuditMsg(entity.getAuditMsg());
        if (entity.getAuditTime() != null) {
            bean.setAuditTime(SimpleDateFormatCache.getYmdhms().format(entity.getAuditTime()));
        }
        bean.setAuditUser(baseUserDao.getBaseUserNameById(entity.getAuditUserId()));
        bean.setCheckMsg(entity.getCheckRemark());
        bean.setCheckState(entity.getCheckState());
        if (entity.getCheckTime() != null) {
            bean.setCheckTime(SimpleDateFormatCache.getYmdhms().format(entity.getCheckTime()));
        }
        if (entity.getCheckUserId() != null) {
            bean.setCheckUser(baseUserDao.getBaseUserNameById(entity.getCheckUserId()));
        }
    }

    private List<BpWorkSafetyApplyUserDetailBean> queryPeopleInfo(BpWorkSafetyCert entity) {
        return bpWorkSafetyCertUserService.findUsersByCertTypeAndWorkId(entity.getId());
    }

    private List<BpWorkSafetyApplyMethodEditBean> querySafetyMethods(BpWorkSafetyCert entity) {
        return bpWorkSafetyCertMethodService.findByCertTypeAndId(entity.getId());
    }

    //动火分析记录
    private List<BpWorkSafetyWebFileBean> queryWebFileBeam(BpWorkSafetyCert entity) {
        List<BpWorkSafetyWebFileBean> list = new ArrayList<>();
        if (entity.getId() != null) {
            List<BpWorkSafetyFileAnalyze> aList = bpWorkSafetyFileAnalyzeDao.findByCertId(entity.getId());
            if (!CollectionUtils.isEmpty(aList)) {
                for (BpWorkSafetyFileAnalyze analyze : aList) {
                    BpWorkSafetyWebFileBean bean = new BpWorkSafetyWebFileBean();
                    BeanUtils.copyProperties(analyze, bean);
                    //分析人姓名
                    if (analyze.getUserId() != null) {
                        if (analyze.getUserType() != null && analyze.getUserType() == 1) {
                            bean.setUserName(bpContractorStaffService.getNameById(analyze.getUserId()));
                        } else {
                            Optional<BaseUser> obu = baseUserDao.findById(analyze.getUserId());
                            if (obu.isPresent()) {
                                bean.setUserName(obu.get().getRealName());
                            }
                        }
                    }
                    list.add(bean);
                }
            }
        }
        return list;
    }

    //受限空间分析记录
    private List<BpWorkSafetyWebSpaceBean> queryWebSpaceBean(BpWorkSafetyCert entity) {
        List<BpWorkSafetyWebSpaceBean> list = new ArrayList<>();
        if (entity.getId() != null) {
            List<BpWorkSafetySpaceAnalyze> aList = bpWorkSafetySpaceAnalyzeDao.findByCertId(entity.getId());
            if (!CollectionUtils.isEmpty(aList)) {
                for (BpWorkSafetySpaceAnalyze analyze : aList) {
                    BpWorkSafetyWebSpaceBean bean = new BpWorkSafetyWebSpaceBean();
                    BeanUtils.copyProperties(analyze, bean);
                    if (analyze.getUserId() != null) {
                        if (analyze.getUserType() != null && analyze.getUserType() == 1) {
                            bean.setUserName(bpContractorStaffService.getNameById(analyze.getUserId()));
                        } else {
                            Optional<BaseUser> obu = baseUserDao.findById(analyze.getUserId());
                            if (obu.isPresent()) {
                                bean.setUserName(obu.get().getRealName());
                            }
                        }
                    }
                    list.add(bean);
                }
            }
        }
        return list;
    }

    private String getDepartname(Long departId) {
        if (departId != null) {
            return bpDepartDao.getOne(departId).getName();
        }
        return null;
    }

    protected String parseWorkTime(BpWorkSafetyCert f) {
        return SimpleDateFormatCache.getYmdZC().format(f.getStartTime()) + " - "
                + SimpleDateFormatCache.getYmdZC().format(f.getEndTime());
    }

    @Override
    public BpWorkSafetyCert add(BpWorkSafetyCertEditBaseBean entity, SafetyWorkTypes type, String module) {
        BpWorkSafetyCert save = null;
        try {
            validateStartAndEndTime(entity);
            BpWorkSafetyCert content = new BpWorkSafetyCert();
            // 作业证编号
            setCode(content, entity, type);
            // 作业类型
            content.setType(type.getName());
            // 作业级别
            content.setWorkLevel(entity.getWorkLevel());
            // 作业开始时间
            content.setStartTime(entity.getStartTime());
            // 作业结束时间
            content.setEndTime(entity.getEndTime());
            if (entity.getApplyTime() == null) {
                content.setApplyTime(new Date());
            } else {
                content.setApplyTime(entity.getApplyTime());
            }
            // 状态
            if (entity.getFlag() != null && entity.getFlag() == 0) {
                //作业证app申请完成后,状态为待审核
                content.setState(SafetyWorkStates.WAITING_FOR_AUDIT.getId());
            } else {
                content.setState(SafetyWorkStates.INITIAL.getId());
            }
            // 申请单位
            content.setApplyDepartId(entity.getApplyDepartId());
            // 申请人
            content.setApplyUserId(entity.getApplyUserId());
            // 作业内容
            content.setWorkContent(entity.getWorkContent());
            // 所属风险区域
            content.setRiskDistrictId(entity.getRiskDistrictId());
            // 作业区域地点
            if (entity.getFlag() != null && entity.getFlag() == 0) {
                //app作业区域
                content.setLocationCoords(getAppCoordinateString(entity.getRiskDistrictId()));
            } else {
                content.setLocationCoords(entity.getLocationCoords());
            }
            // 监护人
            content.setMonitorUserCode(entity.getMonitorUserCode());
            // 实施安全教育人
            content.setEducationUserCode(entity.getEducationUserCode());
            // 风险点
            content.setRiskPointId(entity.getRiskPointId());
            // 风险级别
            content.setRiskLevel(entity.getRiskLevel());

            content.setAlarm(entity.getAlarm());
            // 附件ID
            if (entity.getAttachment() != null) {
                content.setAttachmentId(entity.getAttachment().getId());
            }
            //工作地点
            content.setJobSite(entity.getJobSite());
            // 危害辨识
            content.setDangerRecoganize(entity.getDangerRecoganize());
            // 编制人
            content.setEditUserId(entity.getEditUserId());
            //涉及其他特殊作业证
            if (!CollectionUtils.isEmpty(entity.getOtherSpecialWorkId())) {
                content.setOtherSpecialWorkId(JSON.toJSONString(entity.getOtherSpecialWorkId()));
            }
            content.setWorkToolName(entity.getWorkToolName());
            content.setJhaEvaluationId(entity.getJhaEvaluationId());

            //是否需用电申请签单
            content.setNeedEletricityApplySheet(entity.getNeedEletricityApplySheet());
            //编制人证书
            if (!CollectionUtils.isEmpty(entity.getEditUserCertIds())) {
                content.setEditUserCertIdJson(JSON.toJSONString(entity.getEditUserCertIds()));
            }

            //申请人证书
            if (!CollectionUtils.isEmpty(entity.getApplyUserCertIds())) {
                content.setApplyUserCertIdJson(JSON.toJSONString(entity.getApplyUserCertIds()));
            }
            //监护人证书
            if (!CollectionUtils.isEmpty(entity.getMonitorUserCertIds())) {
                content.setMonitorUserCertIdJson(JSON.toJSONString(entity.getMonitorUserCertIds()));
            }
            //实施安全教育人证书
            if (!CollectionUtils.isEmpty(entity.getEducationUserCertIds())) {
                content.setEducationUserCertIdJson(JSON.toJSONString(entity.getEducationUserCertIds()));
            }

            setExtraInfo(content, entity, type);
            //作业证人员分类
            if (entity.getPeopleTypeBean() != null) {
                content.setPeopleTypeJson(JSON.toJSONString(entity.getPeopleTypeBean()));
            }
            save = dao.save(content);
//            if (type == SafetyWorkTypes.MANG_BAN_CHOU_DU) {
//                //保存盲板抽堵操作人副本信息(完整信息在 setExtraInfo 方法里面)
//                saveMangBanChouDuPeople(content, entity);
//            } else {
//                // 保存操作人相关信息
            saveOperatorUsers(content, entity.getOperatorUserCertDtos());
//            }
            // 保存安全措施
            saveOpMethods(content, entity.getSafetyMethods());
            //保存受限空间分析
            if (type == SafetyWorkTypes.SHOU_XIAN_KONG_JIAN) {
                saveWebSpaceAnalyze(content, entity.getWebSpaceBeans());
            }

            saveTaskList(module, save);
            if (entity.getJhaEvaluationId() != null) {
                // 将作业证和风险评估建立关联
                riskEvaluationRepoService.updateRelatedWorkSafetyCertInfo(entity.getJhaEvaluationId(), save.getId());
            }

            //保存危害辨识表
            saveIdentify(save, entity.getDangerRecoganize(), 0, "危害辨识");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        //设置审核流程
        saveFirstProcess(save.getId());
        return save;
    }

    //设置审核流程
    private void saveFirstProcess(Long id) {
        //审核过程
        BpWorkSafetyAuditProcess process = new BpWorkSafetyAuditProcess();
        List<BpWorkSafetyAuditProcess> sList = bpWorkSafetyAuditProcessDao.getListByCertId(id);
        if (sList.size() == 0) {
            process = new BpWorkSafetyAuditProcess();
        } else if (sList.size() == 1) {
            process = sList.get(0);
        }
        BpWorkSafetyCert cert = dao.findById(id).orElseThrow(() -> new IllegalArgumentException("作业证不存在"));
        //获取审核模板
        List<BpWorkSafetyAuditTemplate> tList = new ArrayList<>();
        if (cert.getType() != null && cert.getWorkLevel() == null) {
            tList = bpWorkSafetyAuditTemplateDao.findByType(cert.getType());
        } else if (cert.getType() != null && cert.getWorkLevel() != null) {
            tList = bpWorkSafetyAuditTemplateDao.findByTypeAndWorkLevel(cert.getType(), cert.getWorkLevel());
        }
//        if (CollectionUtils.isEmpty(tList)) {
//            throw new IllegalArgumentException("请先设置作业证审核模板");
//        }
        //目前一个作业证只有一个模板
        //1.模板不为空,且模板状态为空或者为启用状态->启用模板;2.模板为空或者模板状态为弃用->禁用模板
        if (!CollectionUtils.isEmpty(tList) && (tList.get(0).getState() == null || tList.get(0).getState() == 1)) {
            //启用模板
            process = setUseModelProcess(tList, process);
        } else if (CollectionUtils.isEmpty(tList) || tList.get(0).getState() == 0) {
            //禁用模板
            process = setAbandonModelProcess(process, cert);
        }
        //设置审核步骤为第一步
        process.setStep(0);
        process.setCertId(id);
        bpWorkSafetyAuditProcessDao.save(process);
    }

    //模板启用时设置审核流程
    private BpWorkSafetyAuditProcess setUseModelProcess(List<BpWorkSafetyAuditTemplate> tList, BpWorkSafetyAuditProcess process) {
        //如果模板启用了,从模板中获取审核流程第一个审核人
        BpWorkSafetyAuditProcessAddBean aBean = JSONObject.parseObject(tList.get(0).getProcessJson(),
                BpWorkSafetyAuditProcessAddBean.class);
        if (aBean.getProcessBeans().get(0) != null) {
            //下一个审核对象id
            process.setNextAuditorId(aBean.getProcessBeans().get(0).getPersonOrDepartId());
            //下一个审核人类型:0岗位;1人员
            process.setNextAuditorType(aBean.getProcessBeans().get(0).getType());
        }
        //保存审核流程
        if (!CollectionUtils.isEmpty(aBean.getProcessBeans())) {
            process.setAuditProcessJson(JSON.toJSONString(aBean.getProcessBeans()));
        }

        return process;

    }

    //模板弃用时设置审核流程
    private BpWorkSafetyAuditProcess setAbandonModelProcess(BpWorkSafetyAuditProcess process, BpWorkSafetyCert cert) {
        //模板弃用,将申请单位负责人和作业单位负责人作为审核人
        //审核过程json
        List<BpWorkSafetyAuditProcessBean> pBeans = new ArrayList<>();
        Long fId = null;
        Long sId = null;
        //申请单位负责人
        if (cert.getApplyDepartId() != null) {
            BpWorkSafetyAuditProcessBean processBean = new BpWorkSafetyAuditProcessBean();
            BpDepart depart = bpDepartDao.findById(cert.getApplyDepartId()).orElseThrow(() -> new IllegalArgumentException("部门不存在"));
            if (depart.getChiefId() != null) {
                processBean.setProcessName("审核流程001");
                process.setNextAuditorId(depart.getChiefId());
                process.setNextAuditorType(1);
                processBean.setPersonOrDepartId(depart.getChiefId());
                processBean.setType(1);
                fId = depart.getChiefId();
                //编辑权限
                pBeans = saveSafetyPermission(pBeans, processBean);
            } else {
                throw new IllegalArgumentException("模板禁用时,申请单位部门负责人不能为空");
            }
        }
        //设置生产单位负责人
        if (cert.getType().equals("动火")) {
            if (StringUtils.isNotBlank(cert.getWorkOtherInfoEntityJson())) {
                BpWorkSafetyCertFireEditBean fb = JSONObject.parseObject(cert.getWorkOtherInfoEntityJson(),
                        BpWorkSafetyCertFireEditBean.class);
                if (fb != null && StringUtils.isNotBlank(fb.getProductionDepartResponsibleUserId())) {
                    BpWorkSafetyAuditProcessBean processBean = new BpWorkSafetyAuditProcessBean();
                    if (fId == null) {
                        //无申请单位负责人
                        processBean.setProcessName("审核流程001");
                        process.setNextAuditorId(parseLong(fb.getProductionDepartResponsibleUserId()));
                        process.setNextAuditorType(1);
                    } else {
                        processBean.setProcessName("审核流程002");
                    }
                    processBean.setPersonOrDepartId(parseLong(fb.getProductionDepartResponsibleUserId()));
                    processBean.setType(1);
                    sId = parseLong(fb.getProductionDepartResponsibleUserId());
                    //编辑权限
                    pBeans = saveSafetyPermission(pBeans, processBean);
                }
            }
        } else if (cert.getType().equals("受限空间")) {
            if (StringUtils.isNotBlank(cert.getWorkOtherInfoEntityJson())) {
                BpWorkSafetyCertRestrictedSpaceEditBean store = parse(BpWorkSafetyCertRestrictedSpaceEditBean.class,
                        cert.getWorkOtherInfoEntityJson());
                if (store != null && StringUtils.isNotBlank(store.getOpDepartResponsibleUserCode())) {
                    BpWorkSafetyAuditProcessBean processBean = new BpWorkSafetyAuditProcessBean();
                    if (fId == null) {
                        //无申请单位负责人
                        processBean.setProcessName("审核流程001");
                        process.setNextAuditorId(parseLong(store.getOpDepartResponsibleUserCode()));
                        process.setNextAuditorType(1);
                    } else {
                        processBean.setProcessName("审核流程002");
                    }
                    processBean.setPersonOrDepartId(parseLong(store.getOpDepartResponsibleUserCode()));
                    processBean.setType(1);
                    sId = parseLong(store.getOpDepartResponsibleUserCode());
                    //编辑权限
                    pBeans = saveSafetyPermission(pBeans, processBean);
                }
            }
        } else if (cert.getType().equals("高处")) {
            if (StringUtils.isNotBlank(cert.getWorkOtherInfoEntityJson())) {
                BpWorkSafetyCertHighEditBean store = parse(BpWorkSafetyCertHighEditBean.class,
                        cert.getWorkOtherInfoEntityJson());
                if (store != null && StringUtils.isNotBlank(store.getWorkDepartCode())) {
                    BpWorkSafetyAuditProcessBean processBean = new BpWorkSafetyAuditProcessBean();
                    BpDepart depart = bpDepartDao.findById(parseLong(store.getWorkDepartCode())).orElseThrow(() -> new IllegalArgumentException("部门不存在"));
                    if (depart != null && depart.getChiefId() != null) {
                        if (fId == null) {
                            //无申请单位负责人
                            processBean.setProcessName("审核流程001");
                            process.setNextAuditorId(depart.getChiefId());
                            process.setNextAuditorType(1);
                        } else {
                            processBean.setProcessName("审核流程002");
                        }
                        processBean.setPersonOrDepartId(depart.getChiefId());
                        processBean.setType(1);
                        sId = depart.getChiefId();
                        //编辑权限
                        pBeans = saveSafetyPermission(pBeans, processBean);
                    }
                }
            }
        } else if (cert.getType().equals("盲板抽堵")) {
            if (StringUtils.isNotBlank(cert.getWorkOtherInfoEntityJson())) {
                BpWorkSafetyCertBlindPlateEditBean store = parse(BpWorkSafetyCertBlindPlateEditBean.class,
                        cert.getWorkOtherInfoEntityJson());
                if (store != null && StringUtils.isNotBlank(store.getOpDepartCommanderCode())) {
                    BpWorkSafetyAuditProcessBean processBean = new BpWorkSafetyAuditProcessBean();
                    if (fId == null) {
                        //无申请单位负责人
                        processBean.setProcessName("审核流程001");
                        process.setNextAuditorId(parseLong(store.getOpDepartCommanderCode()));
                        process.setNextAuditorType(1);
                    } else {
                        processBean.setProcessName("审核流程002");
                    }
                    processBean.setPersonOrDepartId(parseLong(store.getOpDepartCommanderCode()));
                    processBean.setType(1);
                    sId = parseLong(store.getOpDepartCommanderCode());
                    //编辑权限
                    pBeans = saveSafetyPermission(pBeans, processBean);
                }
            }
        } else if (cert.getType().equals("动土")) {
            if (StringUtils.isNotBlank(cert.getWorkOtherInfoEntityJson())) {
                BpWorkSafetyCertBreakGroundEditBean store = parse(BpWorkSafetyCertBreakGroundEditBean.class,
                        cert.getWorkOtherInfoEntityJson());
                if (store != null && StringUtils.isNotBlank(store.getWorkDepartCode())) {
                    BpWorkSafetyAuditProcessBean processBean = new BpWorkSafetyAuditProcessBean();
                    BpDepart depart = bpDepartDao.findById(parseLong(store.getWorkDepartCode())).orElseThrow(() -> new IllegalArgumentException("部门不存在"));
                    if (depart != null && depart.getChiefId() != null) {
                        if (fId == null) {
                            //无申请单位负责人
                            processBean.setProcessName("审核流程001");
                            process.setNextAuditorId(depart.getChiefId());
                            process.setNextAuditorType(1);
                        } else {
                            processBean.setProcessName("审核流程002");
                        }
                        processBean.setPersonOrDepartId(depart.getChiefId());
                        processBean.setType(1);
                        sId = depart.getChiefId();
                        //编辑权限
                        pBeans = saveSafetyPermission(pBeans, processBean);
                    }
                }
            }
        } else if (cert.getType().equals("断路")) {
            if (StringUtils.isNotBlank(cert.getWorkOtherInfoEntityJson())) {
                BpWorkSafetyCertBreakRoadEditBean store = parse(BpWorkSafetyCertBreakRoadEditBean.class,
                        cert.getWorkOtherInfoEntityJson());
                if (store != null && StringUtils.isNotBlank(store.getOpDepartResponsibleUserCode())) {
                    BpWorkSafetyAuditProcessBean processBean = new BpWorkSafetyAuditProcessBean();
                    if (fId == null) {
                        //无申请单位负责人
                        processBean.setProcessName("审核流程001");
                        process.setNextAuditorId(parseLong(store.getOpDepartResponsibleUserCode()));
                        process.setNextAuditorType(1);
                    } else {
                        processBean.setProcessName("审核流程002");
                    }
                    processBean.setPersonOrDepartId(parseLong(store.getOpDepartResponsibleUserCode()));
                    processBean.setType(1);
                    sId = parseLong(store.getOpDepartResponsibleUserCode());
                    //编辑权限
                    pBeans = saveSafetyPermission(pBeans, processBean);

                }
            }
        }
        if (fId == null && sId == null) {
            throw new IllegalArgumentException("该作业证无申请单位负责人和作业单位负责人,无法审核");
        }
        //save8SafetyHead(cert, process, pBeans, fId, sId);
        process.setAuditProcessJson(JSON.toJSONString(pBeans));
        return process;
    }


    //保存审核流程编辑权限
    private List<BpWorkSafetyAuditProcessBean> saveSafetyPermission(List<BpWorkSafetyAuditProcessBean> pBeans, BpWorkSafetyAuditProcessBean processBean) {
        List<BpWorkSafetyAuditPermissionBean> permissionBeans = new ArrayList<>();
        BpWorkSafetyAuditPermissionBean permissionBean1 = new BpWorkSafetyAuditPermissionBean();
        BpWorkSafetyAuditPermissionBean permissionBean2 = new BpWorkSafetyAuditPermissionBean();
        //危害辨识权限
        permissionBean1.setPermissionId(0);
        //安全措施权限
        permissionBean2.setPermissionId(1);
        permissionBeans.add(permissionBean1);
        permissionBeans.add(permissionBean2);
        processBean.setPermissionBeans(permissionBeans);
        pBeans.add(processBean);
        return pBeans;
    }

    //保存盲板抽堵作业人员信息
    private void saveMangBanChouDuPeople(BpWorkSafetyCert content, BpWorkSafetyCertEditBaseBean entity) {
        BpWorkSafetyCertBlindPlateEditBean detailBean = (BpWorkSafetyCertBlindPlateEditBean) entity;
        List<BpWorkSafetyCertBlindPlatePeopleBean> peopleBeans = detailBean.getPeopleBeans();
        if (!CollectionUtils.isEmpty(peopleBeans)) {
            List<OperatorUserCertDto> pcdList = new ArrayList();
            List<OperatorUserCertDto> gcdList = new ArrayList();
            for (BpWorkSafetyCertBlindPlatePeopleBean pb : peopleBeans) {
                //作业人员,构造OperatorUserCertDto
                OperatorUserCertDto pDto = new OperatorUserCertDto();
                List<Long> pList = new ArrayList();
                List<OperatorCertAddDto> peopleDto = pb.getPeopleDto();
                if (!CollectionUtils.isEmpty(peopleDto)) {
                    for (OperatorCertAddDto pcd : peopleDto) {
                        //作业证信息
                        pList.add(pcd.getId());
                    }
                }
                pDto.setOperatorUserCertIds(pList);
                pDto.setUserId(pb.getPeopleId());
                pDto.setPeopleType(pb.getPeopleType());
                pcdList.add(pDto);

                //监护人员
                OperatorUserCertDto gDto = new OperatorUserCertDto();
                List<Long> gList = new ArrayList();
                List<OperatorCertAddDto> guardianDto = pb.getGuardianDto();
                if (!CollectionUtils.isEmpty(guardianDto)) {
                    for (OperatorCertAddDto gcd : guardianDto) {
                        //作业证信息
                        gList.add(gcd.getId());
                    }
                }
                gDto.setOperatorUserCertIds(gList);
                gDto.setUserId(pb.getGuardianId());
                gDto.setPeopleType(pb.getGuardianType());
                gcdList.add(gDto);

            }
            //保存
            saveOperatorUsers(content, pcdList);
            saveOperatorUsers(content, gcdList);
        }

    }

    //保存受限空间分析
    private void saveWebSpaceAnalyze(BpWorkSafetyCert content, List<BpWorkSafetyWebSpaceBean> webSpaceBeans) {
        if (!CollectionUtils.isEmpty(webSpaceBeans)) {
            for (BpWorkSafetyWebSpaceBean bean : webSpaceBeans) {
                BpWorkSafetySpaceAnalyze analyze;
//                if (bean.getId() != null) {
//                    analyze = bpWorkSafetySpaceAnalyzeDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("受限空间分析不存在"));
//                } else {
                analyze = new BpWorkSafetySpaceAnalyze();
//                }
                BeanUtils.copyProperties(bean, analyze);
                analyze.setCertId(content.getId());
                analyze.setType(content.getType());
//                Long sId = saveSinger(content, bean.getUserId(), 2, "分析人");
//                analyze.setSignerId(sId);
                bpWorkSafetySpaceAnalyzeDao.save(analyze);
            }
        }
    }

    private void validateStartAndEndTime(BpWorkSafetyCertEditBaseBean entity) {
        validateStartAndEndTime(entity.getStartTime(), entity.getEndTime());
    }

    private void validateStartAndEndTime(Date startTime, Date endTime) {
        if (startTime != null && endTime != null) {
            Assert.isTrue(endTime.after(startTime), "结束时间必须大于开始时间");
        }
    }

    private void saveTaskList(String module, BpWorkSafetyCert save) {
        // 添加代办事项
        BpTaskList bpTaskList = new BpTaskList();
        bpTaskList.setDataId(save.getId());
        bpTaskList.setUserId(save.getApplyUserId());
        bpTaskList.setModule(module);
        taskListDao.save(bpTaskList);
    }

    private void setExtraInfo(BpWorkSafetyCert content, BpWorkSafetyCertEditBaseBean entity, SafetyWorkTypes type) {
        GsonBuilder builder = new GsonBuilder().addSerializationExclusionStrategy(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes f) {
                return f.getDeclaringClass() == BpWorkSafetyCertEditBaseBean.class;
            }

            @Override
            public boolean shouldSkipClass(Class<?> clazz) {
                return false;
            }
        });
        String json = builder.create().toJson(entity);
        content.setWorkOtherInfoEntityJson(json);

    }

    //作业证编码
    private void setCode(BpWorkSafetyCert content, BpWorkSafetyCertEditBaseBean entity, SafetyWorkTypes type) {
        if (StringUtils.isBlank(entity.getCode())) {
            if (type == SafetyWorkTypes.DONG_HUO) {
                content.setCode(bizCodeGeneratorFacade.dongHuoZuoYe());
            } else if (type == SafetyWorkTypes.DONG_TU) {
                content.setCode(bizCodeGeneratorFacade.dongtuZuoYe());
            } else if (type == SafetyWorkTypes.DIAO_ZHUANG) {
                content.setCode(bizCodeGeneratorFacade.diaoZhuangZuoYe());
            } else if (type == SafetyWorkTypes.DUAN_LU) {
                content.setCode(bizCodeGeneratorFacade.duanLuZuoYe());
            } else if (type == SafetyWorkTypes.GAO_CHU) {
                content.setCode(bizCodeGeneratorFacade.gaoChuZuoYe());
            } else if (type == SafetyWorkTypes.LIN_SHI_YONG_DIAN) {
                content.setCode(bizCodeGeneratorFacade.linShiYongDianZuoYe());
            } else if (type == SafetyWorkTypes.MANG_BAN_CHOU_DU) {
                content.setCode(bizCodeGeneratorFacade.mangBanChouDuZuoYe());
            } else if (type == SafetyWorkTypes.SHOU_XIAN_KONG_JIAN) {
                content.setCode(bizCodeGeneratorFacade.shouXianKongJianZuoYe());
            } else if (type == SafetyWorkTypes.YI_BAN) {
                content.setCode(bizCodeGeneratorFacade.yibanZuoYe());
            }
        } else {
            content.setCode(entity.getCode());
        }
    }

    @Override
    public int specialWorkCount() {
        return (int) dao.specialWorkCount();
    }

    @Override
    public SafetyWorkCertStats statsInProgressionCertsBetweenTime(Date start, Date end) {
        SafetyWorkCertStats re = new SafetyWorkCertStats();
        List<Tuple> stats = dao.inProgressCertsStats(start, end);
        System.out.println(stats.size());
        System.out.println(stats);
        for (Tuple t : stats) {
            String type = (String) t.get("type");
            SafetyWorkTypes st = SafetyWorkTypes.findByName(type);
            if (st == SafetyWorkTypes.DONG_HUO) {
                Integer workLevel = (Integer) t.get("workLevel");
                if (workLevel == null) {
                    continue;
                }
                if (workLevel == 0) {
                    re.setFire0(new Item(t.get("count", Long.class).intValue(), true));
                } else if (workLevel == 1) {
                    re.setFire1(new Item(t.get("count", Long.class).intValue(), true));
                } else if (workLevel == 2) {
                    re.setFire2(new Item(t.get("count", Long.class).intValue(), true));
                }
            } else if (st == SafetyWorkTypes.GAO_CHU) {
                Integer workLevel = (Integer) t.get("workLevel");
                if (workLevel == null) {
                    continue;
                }
                if (workLevel == 0) {
                    re.setHigh0(new Item(t.get("count", Long.class).intValue(), true));
                } else if (workLevel == 1) {
                    re.setHigh1(new Item(t.get("count", Long.class).intValue(), true));
                } else if (workLevel == 2) {
                    re.setHigh2(new Item(t.get("count", Long.class).intValue(), true));
                } else if (workLevel == 3) {
                    re.setHigh3(new Item(t.get("count", Long.class).intValue(), true));
                }
            } else if (st == SafetyWorkTypes.DIAO_ZHUANG) {
                re.setLifting(new Item(t.get("count", Long.class).intValue(), true));
            } else if (st == SafetyWorkTypes.DONG_TU) {
                re.setBreakGround(new Item(t.get("count", Long.class).intValue(), true));
            } else if (st == SafetyWorkTypes.DUAN_LU) {
                re.setBreakRoad(new Item(t.get("count", Long.class).intValue(), true));
            } else if (st == SafetyWorkTypes.LIN_SHI_YONG_DIAN) {
                re.setTempElectricity(new Item(t.get("count", Long.class).intValue(), true));
            } else if (st == SafetyWorkTypes.MANG_BAN_CHOU_DU) {
                re.setBlindPlate(new Item(t.get("count", Long.class).intValue(), true));
            } else if (st == SafetyWorkTypes.SHOU_XIAN_KONG_JIAN) {
                re.setResitrictedSpace(new Item(t.get("count", Long.class).intValue(), true));
            } else if (st == SafetyWorkTypes.YI_BAN) {
                re.setNormal(new Item(t.get("count", Long.class).intValue(), true));
            }
        }
        return re;
    }

    /**
     * 作业证风险点评价打印
     *
     * @param code
     * @return
     */
    @Override
    public Map<String, Object> pointAssessmenPrint(String code) {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("title", "风险点评价记录");
        List<Map<String, String>> jhaMaps = new ArrayList<>();
        //根据作业安全证编码查询作业证
        BpWorkSafetyCert safetyCert = bpWorkSafetyCertDao.findByCode(code);
        if (null != safetyCert) {
            //根据作业证id获取作业报告
            RiskPointEvaluationJha repo = evaluationJhaDao.findJhaById(safetyCert.getJhaEvaluationId());
            //查询风险名称,编码,所在区域,风险分级,分析时间,分析人,数据来源
            Long riskPointId = safetyCert.getRiskPointId();
            RiskPoint point = riskPointDao.getById(riskPointId);
            if (point == null) {
                throw new IllegalArgumentException("风险单元不能为空");
            }
            dataMap.put("pointName", point.getName() == null ? "" : point.getName());
            dataMap.put("pointCode", point.getCode() == null ? "" : point.getCode());

            Long riskDistrictId = safetyCert.getRiskDistrictId();
            String districtName = riskDistrictDao.findNameById(riskDistrictId);
            dataMap.put("districtName", districtName == null ? "" : districtName);
            dataMap.put("riskLevel", riskLevel(point.getRiskLevel()) == null ? null : riskLevel(point.getRiskLevel()));
            dataMap.put("repoRiskLevel", riskLevel(repo.getRiskLevel()) == null ? null : riskLevel(repo.getRiskLevel()));

            if ("一般".equals(safetyCert.getType())) {
                dataMap.put("workType", "一般作业");
            }
            dataMap.put("workType", safetyCert.getType() + "安全作业" == null ? "" : safetyCert.getType() + "安全作业");
            SimpleDateFormat sdf = new SimpleDateFormat();
            sdf.applyPattern("yyyy-MM-dd");
            Date date = new Date();
            dataMap.put("date", sdf.format(date));
            // ShiroUser currentUser = Context.getCurrentUser();
            // dataMap.put("currentUser", currentUser.getRealName() == null ? "" : currentUser.getRealName());
            if (null != repo) {
                dataMap.put("createTime", sdf.format(repo.getAnalyzeTime()) == null ? "" : sdf.format(repo.getAnalyzeTime()));
                dataMap.put("createPeople", repo.getBaseUser().getRealName() == null ? "" : repo.getBaseUser().getRealName());
                dataMap.put("method1", "作业危害分析（JHA）");

                //根据评估id查询jha列表
                Set<RiskPointEvaluationJhaItem> jhas = repo.getRiskPointEvaluationJhaItems();
                ArrayList<RiskPointEvaluationJhaItem> riskPointEvaluationJhaItems = Lists.newArrayList(jhas);
                riskPointEvaluationJhaItems.sort(Comparator.comparing(RiskPointEvaluationJhaItem::getId));
                Iterator<RiskPointEvaluationJhaItem> its = riskPointEvaluationJhaItems.iterator();
                int i = 0;
                while (its.hasNext()) {
                    RiskPointEvaluationJhaItem jha = its.next();
                    Map<String, String> jhaMap = new HashMap<>();
                    if (null != jha) {
                        jhaMap.put("index", String.valueOf(i + 1));
                        jhaMap.put("checkItem", jha.getCheckItem() == null ? "" : jha.getCheckItem());
                        jhaMap.put("riskSource", jha.getRiskSource() == null ? "" : jha.getRiskSource());
                        jhaMap.put("consequence", jha.getConsequence() == null ? "" : jha.getConsequence());
                        //现有措施
                        jhaMap.put("controlMethodTech", jha.getControlMethodTech() == null ? "" : jha.getControlMethodTech());
                        jhaMap.put("controlMethodManage", jha.getControlMethodManage() == null ? "" : jha.getControlMethodManage());
                        jhaMap.put("controlMethodTrain", jha.getControlMethodTrain() == null ? "" : jha.getControlMethodTrain());
                        jhaMap.put("controlMethodProtect", jha.getControlMethodProtect() == null ? "" : jha.getControlMethodProtect());
                        jhaMap.put("controlMethodEmegency", jha.getControlMethodEmegency() == null ? "" : jha.getControlMethodEmegency());
                        //风险评价
                        Float likehood = jha.getLikehood();
                        // BaseTypeGroup groupL = baseTypeGroupDao.findByName(BaseGroupTypes.RISK_JHA_L.getName());
                        // BaseTypeGroupItem lhNme = baseTypeGroupItemDao.findNameByCodeAndTypeGroupId(String.valueOf(likehood), groupL.getId());
                        jhaMap.put("likehood", likehood == null ? "" : String.valueOf(likehood));
                        Float exposure = jha.getExposure();
                        // BaseTypeGroup groupE = baseTypeGroupDao.findByName(BaseGroupTypes.RISK_JHA_E.getName());
                        //BaseTypeGroupItem eName = baseTypeGroupItemDao.findNameByCodeAndTypeGroupId(String.valueOf(exposure), groupE.getId());
                        jhaMap.put("exposure", exposure == null ? "" : String.valueOf(exposure));
                        Float consequenceLevel = jha.getConsequenceLevel();
                        // BaseTypeGroup groupC = baseTypeGroupDao.findByName(BaseGroupTypes.RISK_JHA_C.getName());
                        //BaseTypeGroupItem cName = baseTypeGroupItemDao.findNameByCodeAndTypeGroupId(String.valueOf(Math.round(consequenceLevel)), groupC.getId());
                        jhaMap.put("consequenceLevel", consequenceLevel == null ? "" : String.valueOf(consequenceLevel));
                        jhaMap.put("danger", String.valueOf(jha.getDanger()));
                        jhaMap.put("jhaLevel", riskLevel(jha.getRiskLevel()));
                    }
                    i++;
                    jhaMaps.add(jhaMap);
                }
            }
        }
        dataMap.put("jhaMaps", jhaMaps);
        return dataMap;
    }

    @Override
    public ResultBean todayCert() {
        QBpWorkSafetyCert cert = QBpWorkSafetyCert.bpWorkSafetyCert;
        LocalDateTime startTime = LocalDateTime.of(LocalDate.now(), LocalTime.of(0, 0, 0));
        LocalDateTime endTime = LocalDateTime.of(LocalDate.now(), LocalTime.of(23, 59, 59));
        Date startDate = DateTimeUtil.localDateTime2Date(startTime);
        Date endDate = DateTimeUtil.localDateTime2Date(endTime);
        Predicate predicate = ExpressionUtils.or(cert.startTime.between(startDate, endDate), cert.endTime.between(startDate, endDate));
        Iterable<BpWorkSafetyCert> all = dao.findAll(predicate);
        Iterator<BpWorkSafetyCert> iterator = all.iterator();
        Map<Long, String> districtMap = new HashMap<>();
        while (iterator.hasNext()) {
            BpWorkSafetyCert next = iterator.next();
            districtMap.putIfAbsent(next.getId(), "");
        }
        return ResultBean.success(districtMap.size());
    }

    @Override
    public ResultBean certSummary() {
        return ResultBean.success(CertSummaryDto.getDto(getNdaysRecent(7)));
    }


    /**
     * 删除动火审核分析
     *
     * @param id
     */
    @Override
    public void deleteFileAnalyze(Long id) {
        bpWorkSafetyFileAnalyzeDao.deleteById(id);
    }


    /**
     * 删除受限空间审核分析
     *
     * @param id
     */
    @Override
    public void deleteSpaceAnalyze(Long id) {
        bpWorkSafetySpaceAnalyzeDao.deleteById(id);
    }


    /**
     * app验收作业证
     *
     * @param bean
     * @return
     */
    @Override
    public Integer checkApp(BpWorkSafetyAppAuditBean bean) {
        BpWorkSafetyCert cert = bpWorkSafetyCertDao.findById(bean.getCertId()).orElseThrow(() -> new IllegalArgumentException("作业证不存在"));
        //cert.setCheckRemark(bean.getCheckMessage());
        bean.setSTime(cert.getStartTime());
        bean.setETime(cert.getEndTime());
        if (bean.getETime() != null && bean.getSTime() != null) {
            validateStartAndEndTime(bean.getSTime(), bean.getETime());
            cert.setStartTime(bean.getSTime());
            cert.setEndTime(bean.getETime());
        }
        BpWorkSafetyCert save = new BpWorkSafetyCert();
        //签批
        if (bean.getFlag() == 0) {
            //1.保存危害辨识确认表及所属签字表
            BpWorkSafetyIdentifyBean identifyBean = bean.getIdentifyBean();
            if (identifyBean != null) {
                saveIdentify(identifyBean);
            }
            //2.保存安全措施确认表及所属签字表
            List<BpWorkSafetySigenerBean> methodBeans = bean.getMethodBeans();
            if (!CollectionUtils.isEmpty(methodBeans)) {
                for (BpWorkSafetySigenerBean methodBean : methodBeans) {
                    saveStep(methodBean);
                }
            }

            cert.setState((SafetyWorkStates.IN_WORK.getId()));
            cert.setSignatureTime(new Date());
            save = bpWorkSafetyCertDao.save(cert);

        } else if (bean.getFlag() == 1) {
            //3.保存动火分析和受限空间分析及所属签字表
            if (cert.getType().equals(SafetyWorkTypes.DONG_HUO.getName())) {
                //3.1保存动火分析及所属签字表
                List<BpWorkSafetyFileAnalyzeBean> fileBeans = bean.getFileBeans();
                if (!CollectionUtils.isEmpty(fileBeans)) {
                    for (BpWorkSafetyFileAnalyzeBean fileBean : fileBeans) {
                        saveAppFileAnalyze(fileBean, cert);
                    }
                }

            } else if (cert.getType().equals(SafetyWorkTypes.SHOU_XIAN_KONG_JIAN.getName())) {
                //3.2保存受限空间分析及所属签字表
                List<BpWorkSafetySpaceAnalyzeBean> spaceBeans = bean.getSpaceBeans();
                if (!CollectionUtils.isEmpty(spaceBeans)) {
                    for (BpWorkSafetySpaceAnalyzeBean spaceBean : spaceBeans) {
                        saveSpaceAnalyze(spaceBean, cert);
                    }
                }
            }
            //4.1保存签字确认表
            List<BpWorkSafetySigenerAddBean> signerBeans = bean.getSignerBeans();
            save = bpWorkSafetyCertDao.save(cert);
            if (!CollectionUtils.isEmpty(signerBeans)) {
                for (BpWorkSafetySigenerAddBean signerBean : signerBeans) {
                    saveSinger(signerBean, save);
                }
            }
            //5.app审核提交,web和app同时操作同一作业证并先后提交时,app覆盖web审核状态
            appAudit(save.getId(), bean.getSTime(), bean.getETime(), bean.getCheckMessage());
        }
        return bean.getFlag();
    }


    /**
     * 查询app验收页面
     *
     * @param certId
     * @return
     */
    @Override
    public BpWorkSafetyAppAuditBean getAppCheckById(Long certId) {
        BpWorkSafetyAppAuditBean bean = new BpWorkSafetyAppAuditBean();
        BpWorkSafetyCert cert = bpWorkSafetyCertDao.findById(certId).orElseThrow(() -> new IllegalArgumentException("作业证不存在"));
        bean.setSTime(cert.getStartTime());
        bean.setETime(cert.getEndTime());
        bean.setCheckMessage(cert.getCheckRemark());
        //危害辨识
        BpWorkSafetyIdentifyBean identifyBean = getIdentifyById(certId);
        bean.setIdentifyBean(identifyBean);
        //安全措施
        List<BpWorkSafetySigenerBean> methodBeans = getStep(certId);
        bean.setMethodBeans(methodBeans);
        //动火分析
        if (cert.getType().equals(SafetyWorkTypes.DONG_HUO.getName())) {
            List<BpWorkSafetyFileAnalyzeBean> fileBeans = getFileAnalyze(certId);
            bean.setFileBeans(fileBeans);
        }
        //受限空间分析
        if (cert.getType().equals(SafetyWorkTypes.SHOU_XIAN_KONG_JIAN.getName())) {
            List<BpWorkSafetySpaceAnalyzeBean> spaceBeans = getSpaceAnalyze(certId);
            bean.setSpaceBeans(spaceBeans);
        }
        //签字确认
        List<BpWorkSafetySigenerAddBean> signerBeans = getAppSigner(certId);
        bean.setSignerBeans(signerBeans);
        bean.setState(cert.getState());
        bean.setSateName(SafetyWorkStates.findNameById(cert.getState()));
        return bean;
    }

    /**
     * 查看app审核页面
     *
     * @param certId
     * @return
     */
    @Override
    public BpWorkSafetyAppAuditListBean getAppAuditById(Long certId) {
        BpWorkSafetyAppAuditListBean bean = new BpWorkSafetyAppAuditListBean();
        //危害辨识
        BpWorkSafetyIdentifyBean identifyBean = getIdentifyById(certId);
        bean.setIdentifyBean(identifyBean);
        //安全措施
        List<BpWorkSafetySigenerBean> methodBeans = getStep(certId);
        bean.setMethodBeans(methodBeans);
        //审核过程
        List<BpWorkSafetyAuditProcessDetailBean> pDetailBeans = getProcessDetail(certId);
        bean.setPDetailBeans(pDetailBeans);
        return bean;
    }

    /**
     * 模板审核列表
     *
     * @return
     */
    @Override
    public List<BpWorkSafetyAuditTemplateBean> findTemplateList() {
        List<BpWorkSafetyAuditTemplate> list = bpWorkSafetyAuditTemplateDao.findAll();
        List<BpWorkSafetyAuditTemplateBean> beanList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (BpWorkSafetyAuditTemplate template : list) {
                BpWorkSafetyAuditTemplateBean bean = new BpWorkSafetyAuditTemplateBean();
                BeanUtils.copyProperties(template, bean);
                if (template.getState() == null || template.getState() == 1) {
                    bean.setStateName("启用");
                } else {
                    bean.setStateName("禁用");
                }
                bean.setType(template.getType() + "作业");
                if (template.getAuditerId() != null) {
                    bean.setAuditerName(baseUserDao.findById(template.getAuditerId()).get().getRealName());
                }
                if (template.getWorkLevel() != null) {
                    bean.setWorkLevelName(WorkLevels.findNameById(template.getWorkLevel()) + template.getType());
                }
                if ("动火".equals(template.getType()) && template.getWorkLevel() == 0) {
                    bean.setWorkLevelName("特殊危险");
                }
                beanList.add(bean);
            }
        }
        return beanList;
    }

    /**
     * app申请页面列表展示
     *
     * @return
     */
    @Override
    public ResultBean getAppApplyList(Pageable pageable) {
        List<BpWorkSafetyCert> list = bpWorkSafetyCertDao.findAPPlyAndFailedAudit();
        List<BpWorkSafetyAppListBean> beanList = new ArrayList();
        if (!CollectionUtils.isEmpty(list)) {
            for (BpWorkSafetyCert cert : list) {
                BpWorkSafetyAppListBean bean = safety2ApplyBean(cert);
                if (cert.getCreateBy().equals(Context.getCurrentUserId())) {
                    beanList.add(bean);
                }
            }
        }
        Collections.sort(beanList, new Comparator<BpWorkSafetyAppListBean>() {

            @Override
            public int compare(BpWorkSafetyAppListBean o1, BpWorkSafetyAppListBean o2) {
                if (o1.getState().intValue() == o2.getState().intValue()) {
                    return o2.getId().compareTo(o1.getId());
                } else {
                    return o2.getState().compareTo(o1.getState());
                }

            }
        });
        return getResultBean(pageable, beanList);
    }

    /**
     * app待审核页面展示
     *
     * @return
     */
    @Override
    public ResultBean getAppWaitAuditList(Pageable pageable, String codeOrLevel, Integer state) {
        List<BpWorkSafetyCert> list = bpWorkSafetyCertDao.findByState(1);
        List<BpWorkSafetyCert> alist = new ArrayList();
        List<BpWorkSafetyAppListBean> beanList = new ArrayList();
        if (!CollectionUtils.isEmpty(list)) {
            for (BpWorkSafetyCert cert : list) {
                //审核流程
                BpWorkSafetyAuditProcess process = bpWorkSafetyAuditProcessDao.findByCertId(cert.getId());
                if (process.getNextAuditorId() != null) {
                    if (process.getNextAuditorType() == 0) {
                        if (process.getNextAuditorId().equals(Context.getJobId())) {
                            alist.add(cert);
                        }
                    } else if (process.getNextAuditorType() == 1) {
                        if (process.getNextAuditorId().equals(Context.getCurrentUserId())) {
                            alist.add(cert);
                        }
                    } else {
                        alist.add(cert);
                    }
                }
            }
        }
        if (!CollectionUtils.isEmpty(alist)) {
            for (BpWorkSafetyCert cert : alist) {
                BpWorkSafetyAppListBean bean = safety2ApplyBean(cert);
                if (StringUtils.isNotBlank(codeOrLevel)) {
                    Integer level = RiskPointUtil.findWorkLevelFromText(codeOrLevel);
                    if (level != null && cert.getWorkLevel() == level) {
                        if (codeOrLevel.contains("特殊") || codeOrLevel.contains("特殊危险")) {
                            if (cert.getType().equals("动火")) {
                                beanList.add(bean);
                            }
                        } else if (codeOrLevel.contains("特级")) {
                            if (cert.getType().equals("高处")) {
                                beanList.add(bean);
                            }
                        } else {
                            beanList.add(bean);
                        }
                    } else if (cert.getCode().contains(codeOrLevel)) {
                        beanList.add(bean);
                    }
                } else {
                    beanList.add(bean);
                }
            }
        }
        List<BpWorkSafetyAppListBean> resultList = beanList.stream().sorted((a, b) -> b.getId().intValue() - a.getId().intValue()).collect(Collectors.toList());
        return getResultBean(pageable, resultList);
    }

    /**
     * app待验收页面展示
     *
     * @param pageable
     * @return
     */
    @Override
    public ResultBean getAppWaitCheckList(Pageable pageable) {
        List<BpWorkSafetyCert> list = bpWorkSafetyCertDao.getCheckSafetys(2, 6);
        List<BpWorkSafetyAppListBean> beanList = new ArrayList();
        if (!CollectionUtils.isEmpty(list)) {
            for (BpWorkSafetyCert cert : list) {
                BpWorkSafetyAppListBean bean = safety2ApplyBean(cert);
                beanList.add(bean);
            }
        }
        List<BpWorkSafetyAppListBean> resultList = beanList.stream().sorted((a, b) -> b.getId().intValue() - a.getId().intValue()).collect(Collectors.toList());
        return getResultBean(pageable, resultList);
    }


    private BpWorkSafetyAppListBean safety2ApplyBean(BpWorkSafetyCert cert) {
        BpWorkSafetyAppListBean bean = new BpWorkSafetyAppListBean();
        bean.setId(cert.getId());
        //作业名称
        bean.setSafetyName(appType2Name(cert.getType()));
        //编号
        bean.setCode(cert.getCode());
        //类型
        bean.setType(cert.getType() + "安全作业");
        bean.setTypeName(SafetyWorkTypes.findByName(cert.getType()).getCode());
        //作业级别
        bean.setWorkLevel(cert.getWorkLevel());
        bean.setWorkLevelName(WorkLevels.findNameById(cert.getWorkLevel()));
        if ("动火".equals(cert.getType()) && cert.getWorkLevel() == 0) {
            bean.setWorkLevelName("特殊危险");
        }

        //作业区域
        if (cert.getRiskDistrictId() != null) {
            bean.setRiskDistrictName(riskDistrictDao.findNameById(cert.getRiskDistrictId()));
        }
        //申请人
        if (StringUtils.isNotBlank((cert.getPeopleTypeJson()))) {
            BpWorkSafetyPeopleTypeBean peopleTypeBean = JSONObject.parseObject(cert.getPeopleTypeJson(), BpWorkSafetyPeopleTypeBean.class);
            if (cert.getApplyUserId() != null) {
                if (peopleTypeBean == null) {
                    bean.setApplyUserName(baseUserDao.getBaseUserNameById(cert.getApplyUserId()));
                } else if (peopleTypeBean.getApplyUserType() != null && peopleTypeBean.getApplyUserType() == 1) {
                    bean.setApplyUserName(bpContractorStaffService.getNameById(cert.getApplyUserId()));
                } else {
                    bean.setApplyUserName(baseUserDao.getBaseUserNameById(cert.getApplyUserId()));
                }
            }
        }
        //申请单位
        if (cert.getApplyDepartId() != null) {
            bean.setApplyDepartName(bpDepartDao.findDepartNameById(cert.getApplyDepartId()));
        }
        //申请时间
        bean.setApplyTime(cert.getApplyTime());
        //作业时间
        bean.setWorkTime(parseWorkTime(cert));
        //状态
        bean.setState(cert.getState());
        bean.setStateName(SafetyWorkStates.findNameById(cert.getState()));
        //审核结果
        if (cert.getState() == SafetyWorkStates.CHECK_ACCEPTED.getId()) {
            bean.setAuditResult("通过");
        } else {
            bean.setAuditResult("");
        }
        return bean;
    }

    /**
     * 增加审核模板
     *
     * @param bean
     * @return
     */
    @Override
    public BpWorkSafetyAuditTemplate addTemplate(BpWorkSafetyAuditTemplateBean bean) {
        if (bean.getType() != null && bean.getWorkLevel() == null) {
            List<BpWorkSafetyAuditTemplate> tList = bpWorkSafetyAuditTemplateDao.findByType(bean.getType());
            if (!CollectionUtils.isEmpty(tList)) {
                throw new IllegalArgumentException("该类型审核模板已存在");
            }
        } else if (bean.getType() != null && bean.getWorkLevel() != null) {
            List<BpWorkSafetyAuditTemplate> tList = bpWorkSafetyAuditTemplateDao.findByTypeAndWorkLevel(bean.getType(), bean.getWorkLevel());
            if (!CollectionUtils.isEmpty(tList)) {
                throw new IllegalArgumentException("该类型审核模板已存在");
            }
        }
        if ((bean.getType().equals("动火") || bean.getType().equals("高处")) && bean.getWorkLevel() == null) {
            throw new IllegalArgumentException("请设置作业级别");
        }
        BpWorkSafetyAuditTemplate template = new BpWorkSafetyAuditTemplate();
        if (bean.getState() == null) {
            template.setState(1);
        } else {
            template.setState(bean.getState());
        }
        if (bean.getProcessAddBean() != null) {
            template.setProcessJson(JSON.toJSONString(bean.getProcessAddBean()));
        }
        template.setType(bean.getType());
        template.setWorkLevel(bean.getWorkLevel());
        if (bean.getAuditTime() == null) {
            template.setAuditTime(new Date());
        } else {
            template.setAuditTime(bean.getAuditTime());
        }
        if (bean.getAuditerId() == null) {
            template.setAuditerId(bean.getAuditerId());
        } else {
            template.setAuditerId(Context.getCurrentUserId());
        }
        return bpWorkSafetyAuditTemplateDao.save(template);
    }

    /**
     * 修改审核模板
     *
     * @param bean
     * @return
     */
    @Override
    public BpWorkSafetyAuditTemplate updateTemplate(BpWorkSafetyAuditTemplateBean bean) {
        if (bean.getId() == null) {
            throw new IllegalArgumentException("审核模板不存在");
        }
        BpWorkSafetyAuditTemplate template = bpWorkSafetyAuditTemplateDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("审核模板不存在"));
        //修改前 判断当前有无作业证在用该模板审核
        // checkSafetyTemplate(template);
        template.setProcessJson(JSON.toJSONString(bean.getProcessAddBean()));
        template.setType(bean.getType());
        template.setWorkLevel(bean.getWorkLevel());
        template.setAuditTime(bean.getAuditTime());
        if (bean.getAuditerId() == null) {
            template.setAuditerId(bean.getAuditerId());
        } else {
            template.setAuditerId(Context.getCurrentUserId());
        }
        return bpWorkSafetyAuditTemplateDao.save(template);
    }

    private void checkSafetyTemplate(BpWorkSafetyAuditTemplate template) {
        List<BpWorkSafetyCert> content = new ArrayList<>();
        if (template.getWorkLevel() == null) {
            content = bpWorkSafetyCertDao.findByTemplatleType(template.getType());
        } else {
            content = bpWorkSafetyCertDao.findByTypeAndWorkLevel(template.getType(), template.getWorkLevel());
        }
        if (!CollectionUtils.isEmpty(content)) {
            throw new IllegalArgumentException("当前有作业证正在审核,请勿编辑");
        }
    }

    /**
     * 查看审核模板
     *
     * @param templateId
     * @return
     */
    @Override
    public BpWorkSafetyAuditTemplateBean findTemplateById(Long templateId) {
        BpWorkSafetyAuditTemplate template = bpWorkSafetyAuditTemplateDao.findById(templateId).orElseThrow(() -> new IllegalArgumentException("审核模板不存在"));
        BpWorkSafetyAuditTemplateBean bean = new BpWorkSafetyAuditTemplateBean();
        BeanUtils.copyProperties(template, bean);
        bean.setWorkLevelName(getWorkLevelName(template.getType(), template.getWorkLevel()));
        bean.setAuditerName(getPeopleNameByPeopleId(template.getAuditerId()));
        String processJson = template.getProcessJson();
        if (StringUtils.isNotBlank(processJson)) {
            BpWorkSafetyAuditProcessAddBean aBean = JSONObject.parseObject(processJson,
                    BpWorkSafetyAuditProcessAddBean.class);
            List<BpWorkSafetyAuditProcessBean> processBeans = aBean.getProcessBeans();
            if (!CollectionUtils.isEmpty(processBeans)) {
                for (BpWorkSafetyAuditProcessBean pBean : processBeans) {
                    if (pBean.getType() == 0) {
                        //审核角色-岗位信息
                        pBean.setTypeName("岗位");
                        pBean.setPersonOrDepartName(getJobNameByJobId(pBean.getPersonOrDepartId()));
                        //编辑权限
                        List<BpWorkSafetyAuditPermissionBean> permissionBean = pBean.getPermissionBeans();
                        if (CollectionUtils.isEmpty(permissionBean)) {
                            for (BpWorkSafetyAuditPermissionBean perBean : permissionBean) {
                                if (perBean.getPermissionId() == 0) {
                                    perBean.setPermissionName("危害辨识");
                                } else if (perBean.getPermissionId() == 1) {
                                    perBean.setPermissionName("安全措施");
                                }
                            }
                        }
                    } else if (pBean.getType() == 1) {
                        //审核角色-人员信息
                        pBean.setTypeName("人员");
                        pBean.setPersonOrDepartName(getPeopleNameByPeopleId(pBean.getPersonOrDepartId()));
                        //编辑权限
                        List<BpWorkSafetyAuditPermissionBean> permissionBean = pBean.getPermissionBeans();
                        if (!CollectionUtils.isEmpty(permissionBean)) {
                            for (BpWorkSafetyAuditPermissionBean perBean : permissionBean) {
                                if (perBean.getPermissionId() == 0) {
                                    perBean.setPermissionName("危害辨识");
                                } else if (perBean.getPermissionId() == 1) {
                                    perBean.setPermissionName("安全措施");
                                }
                            }
                        }
                    }
                }
            }
            bean.setProcessAddBean(aBean);
        }
        return bean;
    }

    private String getWorkLevelName(String type, Integer level) {
        String name = WorkLevels.findNameById(level);
        if (type.equals("动火") && level == 0) {
            name = "特殊危险";
        }
        return name;
    }


    /**
     * 作业证web,app审核
     *
     * @param bean
     */
    @Override
    public void safetyAudit(BpWorkSafetyWebAuditBean bean) {
        BpWorkSafetyCert cert = bpWorkSafetyCertDao.findById(bean.getCertId()).orElseThrow(() -> new IllegalArgumentException("作业证不存在"));
        if (cert.getState() != 1) {
            throw new IllegalArgumentException("当前状态不正确");
        }
        //判断当前作业证的审核状态
        BpWorkSafetyAuditProcess process = bpWorkSafetyAuditProcessDao.findByCertId(bean.getCertId());
        //记录审核流程详情
        BpWorkSafetyAuditProcessDetail processDetial = new BpWorkSafetyAuditProcessDetail();
        //1.如果审核过程为空则新建
        if (process == null) {
            throw new IllegalArgumentException("作业审核流程设置有误");
            //webAuditFromFirst(processDetial, bean, aBean, cert);
        } else {
            webAuditNotFirst(processDetial, bean, cert, process);
        }
    }

    //web非第一次多人审核作业证
    private void webAuditNotFirst(BpWorkSafetyAuditProcessDetail processDetial,
                                  BpWorkSafetyWebAuditBean bean, BpWorkSafetyCert cert, BpWorkSafetyAuditProcess process) {

        if (process.getNextAuditorType() == 1) {
            //流程中审核人员类型为"人员"
            if (!process.getNextAuditorId().equals(Context.getCurrentUserId())) {
                throw new IllegalArgumentException("当前人不是模板审核人");
            }
        } else if (process.getNextAuditorType() == 0) {
            //流程中审核人员类型为"岗位"
            if (!process.getNextAuditorId().equals(Context.getJobId())) {
                throw new IllegalArgumentException("当前人不是模板审核人");
            }
        }

        if (StringUtils.isBlank(process.getAuditProcessJson())) {
            throw new IllegalArgumentException("作业审核流程为空");
        }
        //获取作业证申请时已设定好的审核流程
        List<BpWorkSafetyAuditProcessBean> pBeans = JSONObject.parseArray(process.getAuditProcessJson(), BpWorkSafetyAuditProcessBean.class);
        //保存审核过程名称
        processDetial.setProcessName(pBeans.get(process.getStep()).getProcessName());
        //防止多人审核冲突,每一次审核只有一条审核详情记录,如果审核详情条数大于当前审核步骤,说明已经被审核了
        List<BpWorkSafetyAuditProcessDetail> detailList = bpWorkSafetyAuditProcessDetailDao.findByCertId(cert.getId());
        if (detailList.size() > process.getStep()) {
            throw new IllegalArgumentException("该作业证已经被审核");
        }
        if (!CollectionUtils.isEmpty(pBeans)) {
            //审核同意
            if (bean.getYesOrNo() == 0) {
                //判断当前审核是不是最后一个审核步骤
                if (pBeans.size() == process.getStep() + 1) {
                    process.setNextAuditorId(null);
                    process.setNextAuditorType(null);
                    cert.setState(SafetyWorkStates.AUDIT_SUCCESS.getId());
                    cert.setAuditMsg(bean.getAuditorMessage());
                    cert.setAuditTime(new Date());
                    cert.setAuditUserId(Context.getCurrentUserId());
                    BpWorkSafetyCert save = bpWorkSafetyCertDao.save(cert);
                    auditForSafety("success", cert, save, bean.getAuditorMessage());
                    //向申华传送数据
                    dataAccessService.workApply(save);
                } else {
                    //不是最后一个审核步骤,更新审核过程信息
                    process.setNextAuditorType(pBeans.get(process.getStep() + 1).getType());
                    process.setNextAuditorId(pBeans.get(process.getStep() + 1).getPersonOrDepartId());
                    process.setStep(process.getStep() + 1);
                }
            } else {
                //审核不同意.更改作业证审核状态和审核意见 结束审核
                process.setNextAuditorId(null);
                process.setNextAuditorType(null);
                cert.setState(SafetyWorkStates.AUDIT_FAILED.getId());
                cert.setAuditMsg(bean.getAuditorMessage());
                cert.setAuditTime(new Date());
                cert.setAuditUserId(Context.getCurrentUserId());
                BpWorkSafetyCert save = bpWorkSafetyCertDao.save(cert);
                auditForSafety("failed", cert, save, bean.getAuditorMessage());
            }
        } else {
            throw new IllegalArgumentException("作业证审核流程为空");
        }
        //当前审核人
        process.setCurrentAuditorId(Context.getCurrentUserId());
        process.setCertId(bean.getCertId());
        process.setYesOrNo(bean.getYesOrNo());

        //保存危害辨识或者安全措施
        List<BpWorkSafetyAuditPermissionBean> permissionBeans = pBeans.get(process.getStep()).getPermissionBeans();
        for (BpWorkSafetyAuditPermissionBean permissionBean : permissionBeans) {
            if (permissionBean.getPermissionId() == 0) {
                //危害辨识
                if (bean.getIdentifyBean() != null) {
                    saveIdentify(bean.getIdentifyBean());
                }
            } else if (permissionBean.getPermissionId() == 1) {
                //安全措施
                if (bean.getMethodBeans() != null) {
                    for (BpWorkSafetySigenerBean methodBean : bean.getMethodBeans()) {
                        saveStep(methodBean);
                    }
                }
            }
        }
        processDetial.setCertId(bean.getCertId());
        processDetial.setAuditorId(Context.getCurrentUserId());
        processDetial.setAuditorTime(new Date());
        processDetial.setAuditorMessage(bean.getAuditorMessage());
        processDetial.setYesOrNo(bean.getYesOrNo());
        bpWorkSafetyAuditProcessDetailDao.save(processDetial);
        bpWorkSafetyAuditProcessDao.save(process);
    }

    //作业证审核其他处理事项
    private void auditForSafety(String str, BpWorkSafetyCert audit, BpWorkSafetyCert save, String auditMessage) {
        if ("success".equals(str)) {
            // 审核成功，更新状态
            if (audit.getJhaEvaluationId() != null) {
                riskEvaluationRepoService.evaluationTakeEffect(audit.getJhaEvaluationId());
            }
        } else {
            if (audit.getJhaEvaluationId() != null) {
                riskEvaluationRepoService.evaluationAuditFail(audit.getJhaEvaluationId());
            }
        }
        // 当作业证进行处理完成时候，再把代办事件进行更新
        // 根据用户ID查询
        List<BpTaskList> byId = taskListService.findById(save.getId());
        if (byId != null) {
            for (BpTaskList bpTaskList : byId) {
                bpTaskList.setState(1);
                bpTaskList.setDetail("作业审核");
                bpTaskList.setHandleRemark(auditMessage);
                // 处理当前时间
                bpTaskList.setHandleTime(new Date());
                bpTaskList.setHandleUserId(Context.getCurrentUserId());
                taskListDao.save(bpTaskList);
            }
        }
    }

    //根据人员id查人员姓名
    private String getPeopleNameByPeopleId(Long peopleId) {
        if (peopleId != null) {
            BaseUser user = baseUserDao.findById(peopleId).orElseThrow(() -> new IllegalArgumentException("人员不存在"));
            return user.getRealName();
        } else {
            return "";
        }
    }

    //根据岗位id查岗位名称
    private String getJobNameByJobId(Long departId) {
        if (departId != null) {
            BpJob job = bpJobDao.findById(departId).orElseThrow(() -> new IllegalArgumentException("岗位不存在"));
            return job.getName();
        } else {
            return "";
        }
    }

    private ResultBean getResultBean(Pageable pageable, List<BpWorkSafetyAppListBean> dtoList) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        int startIndex = pageNumber * pageSize;
        int endIndex = pageNumber * pageSize + pageSize;
        if (CollectionUtils.isEmpty(dtoList)) {
            return ResultBean.success(new ArrayList<>());
        }
        if (dtoList.size() < startIndex) {
            return ResultBean.success(Lists.newArrayList());
        }
        if (dtoList.size() - startIndex < pageSize) {
            return ResultBean.success(dtoList.subList(startIndex, dtoList.size()));
        }
        return ResultBean.success(dtoList.subList(pageNumber * pageSize, endIndex));
    }

    //获取作业证名称
    private String appType2Name(String type) {
        if (type == null) {
            return "";
        } else if (type.equals("动火")) {
            return "动火作业申请";
        } else if (type.equals("受限空间")) {
            return "受限空间作业申请";
        } else if (type.equals("高处")) {
            return "高处作业申请";
        } else if (type.equals("吊装")) {
            return "吊装作业申请";
        } else if (type.equals("临时用电")) {
            return "临时用电作业申请";
        } else if (type.equals("盲板抽堵")) {
            return "盲板抽堵作业申请";
        } else if (type.equals("动土")) {
            return "动土作业申请";
        } else if (type.equals("断路")) {
            return "断路作业申请";
        } else if (type.equals("一般")) {
            return "一般作业申请";
        } else {
            return "";
        }
    }

    //获取作业证状态名称
    private String safetyState2Stateame(Integer state) {
        if (state == null) {
            return "待申请";
        } else if (state == 1) {
            return "待审核";
        } else if (state == 2) {
            return "审核通过";
        } else if (state == 3) {
            return "审核未通过";
        } else if (state == 4) {
            return "验收通过";
        } else if (state == 5) {
            return "验收未通过";
        } else {
            return "";
        }
    }

    /**
     * 保存危害辨识
     *
     * @param bean
     * @return
     */
    @Override
    public Long saveIdentify(BpWorkSafetyIdentifyBean bean) {
        BpWorkSafetyCert c = bpWorkSafetyCertDao.findById(bean.getCertId()).orElseThrow(() -> new IllegalArgumentException("作业证不存在"));
        if (bean != null) {
            BpWorkSafetyIdentify identify;
            if (bean.getId() != null) {
                identify = bpWorkSafetyIdentifyDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("危害辨识不存在"));
            } else {
                identify = new BpWorkSafetyIdentify();
            }
            BeanUtils.copyProperties(bean, identify);
            //保存签名表
            if (bean.getSigenerBean() != null) {
                BpWorkSafetySigenerBean sBean = bean.getSigenerBean();
                BpWorkSafetySigener sigener = new BpWorkSafetySigener();
                //保存签名人,图片,签名日期集合
                sigener.setSignerJson(JSON.toJSONString(sBean.getListBean()));
                sigener.setCategoryId(0);
                sigener.setCertId(bean.getCertId());
                sigener.setType(c.getType());
//                sigener.setUserId(sBean.getUserId());
//                sigener.setDate(sBean.getDate());
//                sigener.setContent(sBean.getContent());
//                if (sBean.getBaseAttachmentBean() != null) {
//                    sigener.setImageId(sBean.getBaseAttachmentBean().getId());
//                }
                BpWorkSafetySigener saveSinger = bpWorkSafetySigenerDao.save(sigener);
                identify.setSignerId(saveSinger.getId());
            }
            identify.setType(c.getType());
            BpWorkSafetyIdentify save = bpWorkSafetyIdentifyDao.save(identify);
            //更新基础信息-端辨识内容
            BpWorkSafetyCert cert = bpWorkSafetyCertDao.findById(save.getCertId()).orElseThrow(() -> new IllegalArgumentException("作业证书不存在"));
            cert.setDangerRecoganize(save.getContent());
            bpWorkSafetyCertDao.save(cert);
            return save.getId();
        } else {
            return null;
        }
    }

    /**
     * 保存安全措施
     *
     * @param bean
     * @return
     */
    @Override
    public Long saveStep(BpWorkSafetySigenerBean bean) {
        BpWorkSafetyCert c = bpWorkSafetyCertDao.findById(bean.getCertId()).orElseThrow(() -> new IllegalArgumentException("作业证不存在"));
        if (bean != null) {
            BpWorkSafetySigener sigener;
            if (bean.getId() != null) {
                sigener = bpWorkSafetySigenerDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("安全措施不存在"));
                BeanUtils.copyProperties(bean, sigener);
                sigener.setCategoryId(1);
                //保存签名人,图片,签名日期集合
                sigener.setSignerJson(JSON.toJSONString(bean.getListBean()));
                //更改已有措施
                List<BpWorkSafetyCertMethod> methods = bpWorkSafetyCertMethodDao.findBySingerId(bean.getId());
                if (methods.size() != 1 || methods == null) {
                    throw new IllegalArgumentException("安全措施数据错误");
                }
                BpWorkSafetyCertMethod method = methods.get(0);
                //措施内容
                method.setMethod(bean.getContent());
                method.setState(bean.getState());
                method.setConfirmUserCertIdJson("");
                //目前安全措施已有一个确认人
                if (bean.getListBean() != null && !CollectionUtils.isEmpty(bean.getListBean().getJsonBeans())) {
                    method.setConfirmUserId(bean.getListBean().getJsonBeans().get(0).getUserId());
                }
                sigener.setType(c.getType());
                BpWorkSafetySigener save = bpWorkSafetySigenerDao.save(sigener);
                method.setSingerId(save.getId());
                bpWorkSafetyCertMethodDao.save(method);
                return save.getId();
            } else {
                sigener = new BpWorkSafetySigener();
                BeanUtils.copyProperties(bean, sigener);
                sigener.setCategoryId(1);
                //保存签名人,图片,签名日期集合
                sigener.setSignerJson(JSON.toJSONString(bean.getListBean()));
                sigener.setType(c.getType());
                //新增措施
                BpWorkSafetyCertMethod method = new BpWorkSafetyCertMethod();
                method.setMethod(bean.getContent());
                //目前安全措施已有一个确认人
                if (bean.getListBean() != null && !CollectionUtils.isEmpty(bean.getListBean().getJsonBeans())) {
                    method.setConfirmUserId(bean.getListBean().getJsonBeans().get(0).getUserId());
                }
                method.setWorkId(bean.getCertId());
                method.setState(bean.getState());
                method.setConfirmUserCertIdJson("");
                BpWorkSafetySigener save = bpWorkSafetySigenerDao.save(sigener);
                method.setSingerId(save.getId());
                bpWorkSafetyCertMethodDao.save(method);
                return save.getId();
            }
        } else {
            return null;
        }
    }

    /**
     * 保存动火审核分析
     *
     * @param bean
     * @return
     */
    @Override
    public Long saveAppFileAnalyze(BpWorkSafetyFileAnalyzeBean bean, BpWorkSafetyCert cert) {
        BpWorkSafetyFileAnalyze analyze;
        if (bean.getId() != null) {
            analyze = bpWorkSafetyFileAnalyzeDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("动火分析不存在"));
        } else {
            analyze = new BpWorkSafetyFileAnalyze();
        }
        BeanUtils.copyProperties(bean, analyze);
        BpWorkSafetySigenerBean sBean = bean.getSigenerBean();
        BpWorkSafetySigener sigener = new BpWorkSafetySigener();
        sigener.setCategoryId(2);
        sigener.setCertId(bean.getCertId());
        sigener.setType(cert.getType());
        //保存签名人,图片,签名日期集合
        sigener.setSignerJson(JSON.toJSONString(sBean.getListBean()));
//        sigener.setUserId(sBean.getUserId());
//        sigener.setDate(sBean.getDate());
//        if (sBean.getBaseAttachmentBean() != null) {
//            sigener.setImageId(sBean.getBaseAttachmentBean().getId());
//        }
        sigener.setContent(sBean.getContent());
        BpWorkSafetySigener saveSinger = bpWorkSafetySigenerDao.save(sigener);
        analyze.setSignerId(saveSinger.getId());
        analyze.setType(cert.getType());
        BpWorkSafetyFileAnalyze save = bpWorkSafetyFileAnalyzeDao.save(analyze);
        return save.getId();
    }

    /**
     * 保存受限空间分析
     *
     * @param bean
     * @return
     */
    @Override
    public Long saveSpaceAnalyze(BpWorkSafetySpaceAnalyzeBean bean, BpWorkSafetyCert cert) {
        BpWorkSafetySpaceAnalyze analyze;
        if (bean.getId() != null) {
            analyze = bpWorkSafetySpaceAnalyzeDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("受限空间分析表不存在"));
        } else {
            analyze = new BpWorkSafetySpaceAnalyze();
        }
        BeanUtils.copyProperties(bean, analyze);
        BpWorkSafetySigenerBean sBean = bean.getSigenerBean();
        BpWorkSafetySigener sigener = new BpWorkSafetySigener();
        sigener.setCategoryId(2);
        sigener.setCertId(bean.getCertId());
        sigener.setType(cert.getType());
        //保存签名人,图片,签名日期集合
        sigener.setSignerJson(JSON.toJSONString(sBean.getListBean()));
//        sigener.setUserId(sBean.getUserId());
//        sigener.setDate(sBean.getDate());
//        if (sBean.getBaseAttachmentBean() != null) {
//            sigener.setImageId(sBean.getBaseAttachmentBean().getId());
//        }
        sigener.setContent(sBean.getContent());
        BpWorkSafetySigener saveSinger = bpWorkSafetySigenerDao.save(sigener);
        analyze.setSignerId(saveSinger.getId());
        analyze.setType(cert.getType());
        BpWorkSafetySpaceAnalyze save = bpWorkSafetySpaceAnalyzeDao.save(analyze);
        return save.getId();
    }

    /**
     * 保存签字确认
     *
     * @param bean
     * @return
     */
    @Override
    public Long saveSinger(BpWorkSafetySigenerAddBean bean, BpWorkSafetyCert safetyCert) {
        BpWorkSafetySigener sigener;
        if (bean.getId() != null) {
            sigener = bpWorkSafetySigenerDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("签字表不存在"));
        } else {
            sigener = new BpWorkSafetySigener();
        }
        BeanUtils.copyProperties(bean, sigener);
        sigener.setCategoryId(3);
        //保存验收消息
        if (bean.getContent().equals("完工验收")) {
            // BpWorkSafetyCert cert = bpWorkSafetyCertDao.findById(bean.getCertId()).orElseThrow(() -> new IllegalArgumentException("作业证不存在"));
            safetyCert.setCheckRemark(bean.getCheckMessage());
        } else if (StringUtils.isNotBlank(bean.getUnitOpinion())) {
            //作业单位负责人完工确认情况
            safetyCert.setUnitOpinion(bean.getUnitOpinion());
        } else if (StringUtils.isNotBlank(bean.getWorkshopOpinion())) {
            //生产车间(分厂)负责人完工确认情况
            safetyCert.setWorkshopOpinion(bean.getWorkshopOpinion());
        }

        bpWorkSafetyCertDao.save(safetyCert);
        //保存签名人,图片,签名日期集合
        if (bean.getListBean() == null) {
            //没有签字的,不涉及
            sigener.setYesOrNo(2);
        }
        sigener.setSignerJson(JSON.toJSONString(bean.getListBean()));
        BpWorkSafetySigener save = bpWorkSafetySigenerDao.save(sigener);
        return save.getId();
    }


    /**
     * app验收
     *
     * @param certId
     * @return
     */
    @Override
    public void appAudit(Long certId, Date sTime, Date eTime, String checkMessage) {
        List<BpWorkSafetySigener> sList = bpWorkSafetySigenerDao.findByCertIdAndCategoryId(certId, 3);
        Integer flag = 0;
        for (BpWorkSafetySigener signer : sList) {
            if (signer.getYesOrNo() != null && signer.getYesOrNo() == 1) {
                flag = 1;
            }
        }
        BpWorkSafetyCert audit = bpWorkSafetyCertDao.findById(certId).orElseThrow(() -> new IllegalArgumentException("作业证不存在"));
        if (sList == null || eTime == null) {
            audit.setStartTime(sTime);
            audit.setEndTime(eTime);
        }
        if (flag == 1) {
            //验收不通过
            audit.setState(SafetyWorkStates.CHECK_FAILED.getId());
            audit.setCheckUserId(Context.getCurrentUserId());
            audit.setCheckTime(new Date());
            audit.setCheckRemark(checkMessage);
            BpWorkSafetyCert save = bpWorkSafetyCertDao.save(audit);
        } else {
            //验收通过
            audit.setState(SafetyWorkStates.CHECK_ACCEPTED.getId());
            audit.setCheckUserId(Context.getCurrentUserId());
            audit.setCheckTime(new Date());
            audit.setCheckRemark(checkMessage);
            BpWorkSafetyCert save = bpWorkSafetyCertDao.save(audit);
            if (audit.getJhaEvaluationId() != null) {
                RiskEvaluationRepo riskEvaluationRepo = riskEvaluationRepoDao.findByEvaluationId(audit.getJhaEvaluationId());
                riskEvaluationRepoService.evaluationOutOfDate(riskEvaluationRepo.getId());
            }
            List<BpTaskList> byId = taskListService.findById(save.getId());
            if (byId != null) {
                for (BpTaskList bpTaskList : byId) {
                    bpTaskList.setState(2);
                    bpTaskList.setDetail("作业证验收");
                    bpTaskList.setHandleRemark(checkMessage);
                    // 处理当前时间
                    bpTaskList.setHandleTime(new Date());
                    bpTaskList.setHandleUserId(Context.getCurrentUserId());
                    taskListDao.save(bpTaskList);
                }
            }
        }
    }

    /**
     * 查看危害辨识
     *
     * @param id
     * @return
     */
    @Override
    public BpWorkSafetyIdentifyBean getIdentifyById(Long id) {
        BpWorkSafetyIdentify identify = bpWorkSafetyIdentifyDao.findByCertId(id);
        BpWorkSafetyIdentifyBean iBean = new BpWorkSafetyIdentifyBean();
        if (identify == null) {
            return iBean;
        }
        BeanUtils.copyProperties(identify, iBean);
        if (identify.getSignerId() != null) {
            Optional<BpWorkSafetySigener> osi = bpWorkSafetySigenerDao.findById(identify.getSignerId());
            if (!osi.isPresent()) {
                iBean.setSigenerBean(null);
            } else {
                BpWorkSafetySigenerBean sigenerBean = this.Sigener2Bean(osi.get());
                iBean.setSigenerBean(sigenerBean);
            }
        }
        return iBean;
    }


    /**
     * 查看措施确认签字表
     *
     * @param certId
     * @return
     */
    @Override
    public List<BpWorkSafetySigenerBean> getStep(Long certId) {
        List<BpWorkSafetySigenerBean> sList = new ArrayList<>();
        List<BpWorkSafetyCertMethod> methods = bpWorkSafetyCertMethodDao.findByWorkId(certId);
        if (!CollectionUtils.isEmpty(methods)) {
            for (BpWorkSafetyCertMethod method : methods) {
                //证书
                List<Long> longs = JSON.parseArray(method.getConfirmUserCertIdJson(), Long.class);
                List<BpWorkSafetyCertDto> confirmUserCertNames = Lists.newArrayList();
                if (longs != null) {
                    for (Long aLong : longs) {
                        confirmUserCertNames.add(new BpWorkSafetyCertDto(aLong, eduCertificateDao.getNameById(aLong)));
                    }
                }
                BpWorkSafetySigenerBean bean = new BpWorkSafetySigenerBean();
                if (method.getSingerId() != null) {
                    BpWorkSafetySigener sigener = bpWorkSafetySigenerDao.findById(method.getSingerId()).orElseThrow(() -> new IllegalArgumentException("签名表不存在"));
                    if (sigener == null) {
                        continue;
                    }
                    BeanUtils.copyProperties(sigener, bean);
                    //确认人
                    if (StringUtils.isNotBlank(sigener.getSignerJson())) {
                        BpWorkSafetySigenerListBean listBean = JSONObject.parseObject(sigener.getSignerJson(), BpWorkSafetySigenerListBean.class);
                        if (listBean != null) {
                            List<BpWorkSafetySigenerJsonBean> jsonBeans = listBean.getJsonBeans();
                            if (!CollectionUtils.isEmpty(jsonBeans)) {
                                for (BpWorkSafetySigenerJsonBean jsonBean : jsonBeans) {
                                    if (jsonBean != null) {
                                        //确认人
                                        if (jsonBean.getUserId() != null) {
                                            if (method.getConfirmUserType() == null) {
                                                jsonBean.setUserName(getName(baseUserDao.getBaseUserNameById(method.getConfirmUserId()), getCertNameList(confirmUserCertNames)));
                                            } else if (method.getConfirmUserType() == 1) {
                                                jsonBean.setUserName(getName(bpContractorStaffService.getNameById(method.getConfirmUserId()), getCertNameList(confirmUserCertNames)));
                                            } else {
                                                jsonBean.setUserName(getName(baseUserDao.getBaseUserNameById(method.getConfirmUserId()), getCertNameList(confirmUserCertNames)));
                                            }
                                        }
                                        if (jsonBean.getBaseAttachmentBean() != null) {
                                            BaseAttachmentBean attachment = attachmentRepositoryService.findByIdIntoBean(jsonBean.getBaseAttachmentBean().getId());
                                            attachment.setDownloadUrl("/image/view?id=" + attachment.getId());
                                            //"/home/seekcy/wwyt/wwyt-server/upload/images/" + image.getThumbnailPath()
                                            jsonBean.setBaseAttachmentBean(attachment);
                                        }
                                    }
                                }
                            }
                            bean.setListBean(listBean);
                        }
                    }
                }
                bean.setContent(method.getMethod());
                bean.setState(method.getState());
                bean.setStateName(methodType2Name(method.getState()));
                sList.add(bean);
            }
        }
        return sList;
    }


    //获取审核过程详情
    private List<BpWorkSafetyAuditProcessDetailBean> getProcessDetail(Long certId) {
        List<BpWorkSafetyAuditProcessDetailBean> pDetailBeans = new ArrayList();
        List<BpWorkSafetyAuditProcessDetail> list = bpWorkSafetyAuditProcessDetailDao.findByCertId(certId);
        if (!CollectionUtils.isEmpty(list)) {
            for (BpWorkSafetyAuditProcessDetail detail : list) {
                BpWorkSafetyAuditProcessDetailBean pDetailBean = new BpWorkSafetyAuditProcessDetailBean();
                BeanUtils.copyProperties(detail, pDetailBean);
                pDetailBean.setAuditorName(getPeopleNameByPeopleId(detail.getAuditorId()));
                if (detail.getYesOrNo() == 0) {
                    pDetailBean.setYesOrNoName("同意");
                } else if (detail.getYesOrNo() == 1) {
                    pDetailBean.setYesOrNoName("不同意");
                }
                pDetailBeans.add(pDetailBean);
            }
        }
        return pDetailBeans;
    }

    //获取安全措施状态名称
    private String methodType2Name(Integer sate) {
        if (sate == null) {
            return "";
        } else if (sate == 0) {
            return "确认";
        } else if (sate == 1) {
            return "不涉及";
        } else if (sate == 2) {
            return "不符合";
        } else {
            return "";
        }
    }

    /**
     * 查看动火分析表
     *
     * @param certId
     * @return
     */
    @Override
    public List<BpWorkSafetyFileAnalyzeBean> getFileAnalyze(Long certId) {
        List<BpWorkSafetyFileAnalyze> analyzes = bpWorkSafetyFileAnalyzeDao.findByCertId(certId);
        List<BpWorkSafetyFileAnalyzeBean> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(analyzes)) {
            for (BpWorkSafetyFileAnalyze analyze : analyzes) {
                BpWorkSafetyFileAnalyzeBean aBean = new BpWorkSafetyFileAnalyzeBean();
                BeanUtils.copyProperties(analyze, aBean);
                //分析人姓名
                if (analyze.getUserId() != null) {
                    if (analyze.getUserType() != null && analyze.getUserType() == 1) {
                        aBean.setUserName(bpContractorStaffService.getNameById(analyze.getUserId()));
                    } else {
                        Optional<BaseUser> obu = baseUserDao.findById(analyze.getUserId());
                        if (obu.isPresent()) {
                            aBean.setUserName(obu.get().getRealName());
                        }
                    }
                }
                //查签名
                if (analyze.getSignerId() != null) {
                    Optional<BpWorkSafetySigener> osi = bpWorkSafetySigenerDao.findById(analyze.getSignerId());
                    if (!osi.isPresent()) {
                        aBean.setSigenerBean(new BpWorkSafetySigenerBean());
                    } else {
                        BpWorkSafetySigenerBean sigenerBean = this.Sigener2Bean(osi.get());
                        aBean.setSigenerBean(sigenerBean);
                    }
                }
                list.add(aBean);
            }
        }
        return list;
    }

    /**
     * 查看受限空间分析表
     *
     * @param certId
     * @return
     */
    @Override
    public List<BpWorkSafetySpaceAnalyzeBean> getSpaceAnalyze(Long certId) {
        List<BpWorkSafetySpaceAnalyze> analyzes = bpWorkSafetySpaceAnalyzeDao.findByCertId(certId);
        List<BpWorkSafetySpaceAnalyzeBean> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(analyzes)) {
            for (BpWorkSafetySpaceAnalyze analyze : analyzes) {
                BpWorkSafetySpaceAnalyzeBean aBean = new BpWorkSafetySpaceAnalyzeBean();
                BeanUtils.copyProperties(analyze, aBean);
                if (analyze.getUserId() != null) {
                    if (analyze.getUserType() != null && analyze.getUserType() == 1) {
                        aBean.setUserName(bpContractorStaffService.getNameById(analyze.getUserId()));
                    } else {
                        Optional<BaseUser> obu = baseUserDao.findById(analyze.getUserId());
                        if (obu.isPresent()) {
                            aBean.setUserName(obu.get().getRealName());
                        }
                    }
                }
                //查签名
                if (analyze.getSignerId() != null) {
                    Optional<BpWorkSafetySigener> osi = bpWorkSafetySigenerDao.findById(analyze.getSignerId());
                    if (!osi.isPresent()) {
                        aBean.setSigenerBean(new BpWorkSafetySigenerBean());
                    } else {
                        BpWorkSafetySigenerBean sigenerBean = this.Sigener2Bean(osi.get());
                        aBean.setSigenerBean(sigenerBean);
                    }
                }
                list.add(aBean);
            }
        }
        return list;
    }

    /**
     * 查看作业证签字表
     *
     * @param certId
     * @return
     */
    @Override
    public List<BpWorkSafetySigenerBean> getSigner(Long certId, Integer categoryId) {
        List<BpWorkSafetySigener> sigeners = bpWorkSafetySigenerDao.findByCertIdAndCategoryId(certId, categoryId);
        ArrayList<BpWorkSafetySigenerBean> sList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(sigeners)) {
            for (BpWorkSafetySigener sigener : sigeners) {
                BpWorkSafetySigenerBean bean = this.Sigener2Bean(sigener);
                bean.setYesOrNoName(yn2String(sigener.getYesOrNo()));
                sList.add(bean);
            }
        }
        return sList;
    }

    /**
     * app查看签字表
     *
     * @param certId
     * @return
     */
    @Override
    public List<BpWorkSafetySigenerAddBean> getAppSigner(Long certId) {
        List<BpWorkSafetySigener> sigeners = bpWorkSafetySigenerDao.findByCertIdAndCategoryId(certId, 3);
        BpWorkSafetyCert cert = bpWorkSafetyCertDao.findById(certId).orElseThrow(() -> new IllegalArgumentException("作业证不存在"));
        ArrayList<BpWorkSafetySigenerAddBean> sList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(sigeners)) {
            for (BpWorkSafetySigener sigener : sigeners) {
                BpWorkSafetySigenerAddBean sigenerBean = new BpWorkSafetySigenerAddBean();
                sigenerBean.setId(sigener.getId());
                sigenerBean.setCertId(sigener.getCertId());
                sigenerBean.setType(sigener.getType());
                if (sigener.getContent().equals("完工验收")) {
                    sigenerBean.setCheckMessage(cert.getCheckRemark());
                }
                //作业单位负责人完工确认情况
                if (StringUtils.isNotBlank(cert.getUnitOpinion()) && sigener.getContent().equals("作业单位负责人完工确认情况")) {
                    sigenerBean.setUnitOpinion(cert.getUnitOpinion());
                }
                //生产车间(分厂)负责人完工确认情况
                if (StringUtils.isNotBlank(cert.getWorkshopOpinion()) && (sigener.getContent().equals("生产车间(分厂)负责人完工确认情况") ||
                        sigener.getContent().equals("生产车间（分厂）负责人完工确认情况"))) {
                    sigenerBean.setWorkshopOpinion(cert.getWorkshopOpinion());
                }
                sigenerBean.setContent(sigener.getContent());
                sigenerBean.setYesOrNoName(yn2String(sigener.getYesOrNo()));
                //确认人
                if (StringUtils.isNotBlank(sigener.getSignerJson())) {
                    BpWorkSafetySigenerListBean listBean = JSONObject.parseObject(sigener.getSignerJson(), BpWorkSafetySigenerListBean.class);
                    if (listBean != null) {
                        List<BpWorkSafetySigenerJsonBean> jsonBeans = listBean.getJsonBeans();
                        if (!CollectionUtils.isEmpty(jsonBeans)) {
                            for (BpWorkSafetySigenerJsonBean jsonBean : jsonBeans) {
                                if (jsonBean.getUserId() != null) {
                                    BaseUser user = baseUserDao.findById(jsonBean.getUserId()).orElseThrow(() -> new IllegalArgumentException("人员不存在"));
                                    jsonBean.setUserName(user.getRealName());
                                }
                                //图片
                                if (jsonBean.getBaseAttachmentBean() != null) {
                                    BaseAttachmentBean attachment = attachmentRepositoryService.findByIdIntoBean(jsonBean.getBaseAttachmentBean().getId());
                                    BaseAttachmentBean baseAttachmentBean = new BaseAttachmentBean();
                                    baseAttachmentBean.setId(attachment.getId());
                                    baseAttachmentBean.setDownloadUrl(serverUrl + "/image/view?id=" + attachment.getId());
                                    jsonBean.setBaseAttachmentBean(baseAttachmentBean);
                                }
                            }
                        }
                        sigenerBean.setListBean(listBean);
                    }
                }
                sList.add(sigenerBean);
            }
        }
        return sList;
    }

    private String yn2String(Integer sigener) {
        if (sigener == null) {
            return null;
        } else if (sigener == 1) {
            return "不同意";
        } else if (sigener == 0) {
            return "同意";
        } else if (sigener == 2) {
            return "不涉及";
        } else {
            return "";
        }
    }

    private BpWorkSafetySigenerBean Sigener2Bean(BpWorkSafetySigener sigener) {
        BpWorkSafetySigenerBean sigenerBean = new BpWorkSafetySigenerBean();
        BeanUtils.copyProperties(sigener, sigenerBean);

        //确认人
        if (StringUtils.isNotBlank(sigener.getSignerJson())) {
            BpWorkSafetySigenerListBean listBean = JSONObject.parseObject(sigener.getSignerJson(), BpWorkSafetySigenerListBean.class);
            if (listBean != null) {
                List<BpWorkSafetySigenerJsonBean> jsonBeans = listBean.getJsonBeans();
                if (!CollectionUtils.isEmpty(jsonBeans)) {
                    for (BpWorkSafetySigenerJsonBean jsonBean : jsonBeans) {
                        //todo 签字人是否分本公司人员/承包商
                        if (jsonBean.getUserId() != null) {
                            BaseUser user = baseUserDao.findById(jsonBean.getUserId()).orElseThrow(() -> new IllegalArgumentException("人员不存在"));
                            jsonBean.setUserName(user.getRealName());
                        }
                        if (jsonBean.getBaseAttachmentBean() != null) {
                            BaseAttachmentBean attachment = attachmentRepositoryService.findByIdIntoBean(jsonBean.getBaseAttachmentBean().getId());
                            jsonBean.setBaseAttachmentBean(attachment);
                        }
                    }
                }
            }
        }
        return sigenerBean;
    }

    private String riskLevel(Integer level) {
        if (level == null) {
            return "";
        } else if (RiskLevels.DI_FENG_XIAN.getCode() == level) {
            return RiskLevels.DI_FENG_XIAN.getName();
        } else if (RiskLevels.YI_BAN_FENG_XIAN.getCode() == level) {
            return RiskLevels.YI_BAN_FENG_XIAN.getName();
        } else if (RiskLevels.JIAO_DA_FENG_XIAN.getCode() == level) {
            return RiskLevels.JIAO_DA_FENG_XIAN.getName();
        } else if (RiskLevels.ZHONG_DA_FENG_XIAN.getCode() == level) {
            return RiskLevels.ZHONG_DA_FENG_XIAN.getName();
        } else {
            return "";
        }
    }

    //获取证书名称
    private String getCertName(List<Long> longs) {
        List<String> confirmUserCertNames = Lists.newArrayList();
        if (longs != null) {
            for (Long aLong : longs) {
                confirmUserCertNames.add(eduCertificateDao.getNameById(aLong));
            }
        }
        return String.join(",", confirmUserCertNames);
    }


    /**
     * 获取作业证打印数据
     *
     * @param id
     * @param type
     * @return
     */
    @Override
    public Map<String, Object> getSafetyMap(Long id, String type) throws IOException {
        if ("动火".equals(type)) {
            return getFileSafetyMap(id);
        } else if ("受限空间".equals(type)) {
            return getSpaceSafetyMap(id);
        } else if ("高处".equals(type)) {
            return getHighSafetyMap(id);
        } else if ("吊装".equals(type)) {
            return getDiaoZhuangSafetyMap(id);
        } else if ("临时用电".equals(type)) {
            return getLinshiSafetyMap(id);
        } else if ("盲板抽堵".equals(type)) {
            return getMangBanSafetyMap(id);
        } else if ("动土".equals(type)) {
            return getDongTuSafetyMap(id);
        } else if ("断路".equals(type)) {
            return getDuanLuSafetyMap(id);
        } else {
            return null;
        }
    }

    /**
     * 获取动火作业证打印数据
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getFileSafetyMap(Long id) throws IOException {
        BpWorkSafetyApplyFireEditBean data = this.findDetailByIdFire(id);
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, String>> listMap = new ArrayList<Map<String, String>>();
        List<Map<String, Object>> methodListMap = new ArrayList<>();
        List<Map<String, String>> fileListMap = new ArrayList<Map<String, String>>();
        map.put("applyDepartName", data.getApplyDepartName());//申请单位
        map.put("applyUserName", data.getApplyUserName());//申请人
        if (data.getApplyTime() != null) {
            map.put("applyTime", SimpleDateFormatCache.getYmdZC().format(data.getApplyTime()));//申请时间
        }
        map.put("code", data.getCode());//作业证编号
        map.put("stateName", data.getStateName());//状态
        map.put("workLevelName", data.getWorkLevelName());//作业级别
        map.put("jobSite", data.getJobSite());//动火地点
        //动火方式
        if (!CollectionUtils.isEmpty(data.getOpFireMethodBeans())) {
            StringBuilder sb = new StringBuilder();
            for (BpOpFireMethodBean bpOpFireMethodBean : data.getOpFireMethodBeans()) {
                sb.append(bpOpFireMethodBean.getOpFireMethodName()).append(",");
            }
            map.put("opFireMethodName", sb.deleteCharAt(sb.length() - 1));
        }
        map.put("opFireContent", data.getOpFireContent());//动火内容
        map.put("locationCoords", data.getLocationCoords());//动火区域
        if (data.getStartTime() != null) {
            map.put("startTime", SimpleDateFormatCache.getYmdhm().format(data.getStartTime()));//动火开始时间
        }
        if (data.getEndTime() != null) {
            map.put("endTime", SimpleDateFormatCache.getYmdhm().format(data.getEndTime()));//动火结束时间
        }
        map.put("riskDistrictName", data.getRiskDistrictName());//所属风险区域
        map.put("username", data.getProductionDepartResponsibleUserName());//生产单位负责人
        map.put("responsibleUserName", data.getOpFireJobResponsibleUserName());//动火作业负责人
        map.put("aditUserName", data.getOpFireFirstAuditUserName());//动火初审人
        map.put("opFireUserName", data.getOpFireMonitorUserName());//监火人
        map.put("opUserName", data.getOpFireEducationUserName());//实施安全教育人
        map.put("riskLevelName", data.getRiskLevelName());//作业风险评估
        map.put("checkMsg", data.getCheckMsg());//验收消息
        //涉及的其他特殊作业证
        if (!CollectionUtils.isEmpty(data.getBpOtherSpecialWorkBeans())) {
            StringBuilder sb = new StringBuilder();
            for (BpOtherSpecialWorkBean workBean : data.getBpOtherSpecialWorkBeans()) {
                sb.append(workBean.getOtherSpecialWorkName()).append(",");
            }
            map.put("otherSpecialWorkName", sb.deleteCharAt(sb.length() - 1));
        } else {
            map.put("otherSpecialWorkName", "无");
        }
        if (data.getAttachment() != null) {
            map.put("attachment", data.getAttachment().getName());//附件
        }
        map.put("dangerRecoganize", data.getDangerRecoganize());//危害辨识
        map.put("needEletricityApplySheet", data.getNeedEletricityApplySheet());//是否需要电子申请单
        map.put("workToolName", data.getWorkToolName());//工具名称
        map.put("editUserName", data.getEditUserName());//编制人
        //动火分析
        List<BpWorkSafetyFileAnalyze> fileAnalyzes = bpWorkSafetyFileAnalyzeDao.findByCertId(id);
        if (!CollectionUtils.isEmpty(fileAnalyzes)) {
            int a = 1;
            for (BpWorkSafetyFileAnalyze analyze : fileAnalyzes) {
                if (analyze.getDate() != null) {
                    map.put("date" + a, SimpleDateFormatCache.getYmdhm().format(analyze.getDate()));
                }
                //分析点
                map.put("pointName" + a, analyze.getPointName());
                //分析数据
                map.put("data" + a, analyze.getData());
                if (analyze.getSignerId() != null) {
                    Optional<BpWorkSafetySigener> sigenerOp = bpWorkSafetySigenerDao.findById(analyze.getSignerId());
                    if (sigenerOp.isPresent()) {
                        BpWorkSafetySigener sigener = sigenerOp.get();
                        if (StringUtils.isNotBlank(sigener.getSignerJson())) {
                            BpWorkSafetySigenerListBean listBean = JSONObject.parseObject(sigener.getSignerJson(), BpWorkSafetySigenerListBean.class);
                            if (listBean != null) {
                                List<BpWorkSafetySigenerJsonBean> jsonBeans = listBean.getJsonBeans();
                                if (!org.springframework.util.CollectionUtils.isEmpty(jsonBeans)) {
                                    //图片
                                    if (jsonBeans.get(0).getBaseAttachmentBean() != null) {
                                        Long imageId = jsonBeans.get(0).getBaseAttachmentBean().getId();
                                        BaseImageRepository image = baseImageRespositoryDao.findById(imageId).orElseThrow(() -> new IllegalArgumentException("图片不存在"));
                                        String url = "/home/seekcy/wwyt/wwyt-server/upload/images/" + image.getThumbnailPath();
                                        ImageEntity test = new ImageEntity(url, 50, 50);
                                        test.setType(ImageEntity.URL);
                                        map.put("userName" + a, test);//图片
                                    }
                                }
                            }
                        }
                    }
                }
                a++;
            }
        }
        //安全措施
        if (!CollectionUtils.isEmpty(data.getSafetyMethods())) {
            List<BpWorkSafetyApplyMethodEditBean> methods = data.getSafetyMethods();
            int index = 1;
            for (BpWorkSafetyApplyMethodEditBean methodBean : methods) {
                Map<String, Object> maps = new HashMap<>();
                //序号
                map.put("index", String.valueOf(index));
                //措施
                map.put("method" + index, methodBean.getMethod());
                //状态名称
                map.put("stateName" + index, methodBean.getStateName());
                //确认人
                if (StringUtils.isNotBlank(methodBean.getConfirmUserName())) {
                    map.put("confirmUserName" + index, methodBean.getConfirmUserName());
                }
                //图片
                Optional<BpWorkSafetyCertMethod> byId = bpWorkSafetyCertMethodDao.findById(methodBean.getId());
                if (byId.isPresent() && byId.get().getSingerId() != null) {
                    Optional<BpWorkSafetySigener> sigenerOp = bpWorkSafetySigenerDao.findById(byId.get().getSingerId());
                    if (sigenerOp.isPresent()) {
                        BpWorkSafetySigener sigener = sigenerOp.get();
                        if (StringUtils.isNotBlank(sigener.getSignerJson())) {
                            BpWorkSafetySigenerListBean listBean = JSONObject.parseObject(sigener.getSignerJson(), BpWorkSafetySigenerListBean.class);
                            if (listBean != null) {
                                List<BpWorkSafetySigenerJsonBean> jsonBeans = listBean.getJsonBeans();
                                if (!org.springframework.util.CollectionUtils.isEmpty(jsonBeans)) {
                                    //图片
                                    if (jsonBeans.get(0).getBaseAttachmentBean() != null) {
                                        Long imageId = jsonBeans.get(0).getBaseAttachmentBean().getId();
                                        BaseImageRepository image = baseImageRespositoryDao.findById(imageId).orElseThrow(() -> new IllegalArgumentException("图片不存在"));
                                        String url = "/home/seekcy/wwyt/wwyt-server/upload/images/" + image.getThumbnailPath();
                                        ImageEntity test = new ImageEntity(url, 50, 50);
                                        test.setType(ImageEntity.URL);
                                        map.put("confirmUserName" + index, test);//图片
                                    }
                                }
                            }
                        }
                    }
                }
                methodListMap.add(maps);
                index++;
            }
            map.put("s", methodListMap);
        }
        //图片
        Map<String, Object> resultMap = getPhoto(map, id);
        return resultMap;
    }


    /**
     * 图片转为byte数组
     *
     * @param path
     * @return
     */
    private byte[] image2byte(String path) throws IOException {
        byte[] data = null;
        URL url = null;
        InputStream input = null;
        try {
            url = new URL(path);
            HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            input = httpUrl.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int numBytesRead = 0;
        while ((numBytesRead = input.read(buf)) != -1) {
            output.write(buf, 0, numBytesRead);
        }
        data = output.toByteArray();
        output.close();
        input.close();
        return data;
    }

    private String name2ListToString(List<String> list) {
        if (list.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                sb.append(list.get(i)).append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        } else {
            return null;
        }
    }

    /**
     * 获取受限空间打印获数据
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getSpaceSafetyMap(Long id) throws IOException {
        BpWorkSafetyCertDetailBean data = this.getById(id);
        BpWorkSafetyCertRestrictedSpaceDetailBean detail = (BpWorkSafetyCertRestrictedSpaceDetailBean) data;
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, String>> spaceListMap = new ArrayList<Map<String, String>>();
        map.put("sapceDepartName", detail.getSapceDepartName());//受限空间所属单位
        map.put("spaceName", detail.getSpaceName());//受限空间
        map.put("originMediumNameInSpace", detail.getOriginMediumNameInSpace());//受限空间内有介质
        map.put("responsibleUserName", detail.getOpDepartResponsibleUserName());//作业单位负责人
        //受限空间分析
        List<BpWorkSafetySpaceAnalyze> spaceAnalyzes = bpWorkSafetySpaceAnalyzeDao.findByCertId(id);
        if (!CollectionUtils.isEmpty(spaceAnalyzes)) {
            int a = 1;
            for (BpWorkSafetySpaceAnalyze analyze : spaceAnalyzes) {
                //分析时间
                if (analyze.getDate() != null) {
                    map.put("date" + a, SimpleDateFormatCache.getYmdhm().format(analyze.getDate()));
                }
                //项目
                map.put("project" + a, analyze.getProject());
                //标准
                map.put("standard" + a, analyze.getStandard());
                //数据
                map.put("data" + a, analyze.getData());
                //部位
                map.put("part" + a, analyze.getPart());
                //分析人
                if (analyze.getSignerId() != null) {
                    Optional<BpWorkSafetySigener> sigenerOp = bpWorkSafetySigenerDao.findById(analyze.getSignerId());
                    if (sigenerOp.isPresent()) {
                        BpWorkSafetySigener sigener = sigenerOp.get();
                        if (StringUtils.isNotBlank(sigener.getSignerJson())) {
                            BpWorkSafetySigenerListBean listBean = JSONObject.parseObject(sigener.getSignerJson(), BpWorkSafetySigenerListBean.class);
                            if (listBean != null) {
                                List<BpWorkSafetySigenerJsonBean> jsonBeans = listBean.getJsonBeans();
                                if (!org.springframework.util.CollectionUtils.isEmpty(jsonBeans)) {
                                    //图片
                                    if (jsonBeans.get(0).getBaseAttachmentBean() != null) {
                                        Long imageId = jsonBeans.get(0).getBaseAttachmentBean().getId();
                                        BaseImageRepository image = baseImageRespositoryDao.findById(imageId).orElseThrow(() -> new IllegalArgumentException("图片不存在"));
                                        String url = "/home/seekcy/wwyt/wwyt-server/upload/images/" + image.getThumbnailPath();
                                        ImageEntity test = new ImageEntity(url, 50, 50);
                                        test.setType(ImageEntity.URL);
                                        map.put("userName" + a, test);//图片
                                    }
                                }
                            }
                        }
                    }
                }
                a++;
            }
        }
        //共有信息
        Map<String, Object> commonMap = getSafetyCommonContent(map, data);
        //图片
        Map<String, Object> resultMap = getPhoto(commonMap, id);
        return resultMap;
    }

    /**
     * 获取临时用电打印数据
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getLinshiSafetyMap(Long id) throws IOException {
        BpWorkSafetyCertDetailBean data = this.getById(id);
        BpWorkSafetyCertTempElectricityDetailBean detail = (BpWorkSafetyCertTempElectricityDetailBean) data;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("joinInPoint", detail.getJoinInPoint());//电源接入点
        map.put("voltage", detail.getVoltage());//工作电压
        map.put("deviceAndPower", detail.getDeviceAndPower());//作业用电设备及功率
        //共有信息
        Map<String, Object> commonMap = getSafetyCommonContent(map, data);
        //图片
        Map<String, Object> resultMap = getPhoto(commonMap, id);
        return resultMap;
    }

    /**
     * 获取高处打印数据
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getHighSafetyMap(Long id) throws IOException {
        BpWorkSafetyCertDetailBean data = this.getById(id);
        Map<String, Object> map = new HashMap<String, Object>();
        BpWorkSafetyCertHighDetailBean detail = (BpWorkSafetyCertHighDetailBean) data;
        map.put("workHeight", detail.getWorkHeight());//作业高度
        map.put("workDepartName", detail.getWorkDepartName());//作业单位
        //共有信息
        Map<String, Object> commonMap = getSafetyCommonContent(map, data);
        //图片
        Map<String, Object> resultMap = getPhoto(commonMap, id);
        return resultMap;
    }

    /**
     * 获取吊装打印数据
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getDiaoZhuangSafetyMap(Long id) throws IOException {
        BpWorkSafetyCertDetailBean data = this.getById(id);
        Map<String, Object> map = new HashMap<String, Object>();
        BpWorkSafetyCertLiftingDetailBean detail = (BpWorkSafetyCertLiftingDetailBean) data;
        map.put("liftingToolName", detail.getLiftingToolName());//吊装工具名称
        map.put("weight", detail.getWeight());//起吊重物质量
        map.put("liftingOpUserName", detail.getLiftingOpUserName());//吊装人员
        map.put("liftingOpUserCertNo", detail.getLiftingOpUserCertNo());//吊装人员特殊工种作业证号
        map.put("liftingCommanderCertNo", detail.getLiftingCommanderCertNo());//吊装指挥特殊工种作业证号
        map.put("liftingCommanderName", detail.getLiftingCommanderName());//吊装指挥
        map.put("workContent", data.getWorkContent());//工作内容

        //共有信息
        Map<String, Object> commonMap = getSafetyCommonContent(map, data);
        //图片
        Map<String, Object> resultMap = getPhoto(commonMap, id);
        return resultMap;
    }

    /**
     * 获取盲板打印数据
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getMangBanSafetyMap(Long id) throws IOException {
        BpWorkSafetyCertDetailBean data = this.getById(id);
        Map<String, Object> map = new HashMap<String, Object>();
        BpWorkSafetyCertBlindPlateDetailBean detail = (BpWorkSafetyCertBlindPlateDetailBean) data;
        //设备管道名称
        if (StringUtils.isNotBlank(detail.getPipeName())) {
            map.put("pipeName", detail.getPipeName());
        } else {
            map.put("pipeName", detail.getWorkContent());
        }
        map.put("medium", detail.getMedium());//介质
        map.put("temperature", detail.getTemperature());//温度
        map.put("pressure", detail.getPressure());//压力
        map.put("plateMaterial", detail.getPlateMaterial());//盲板-材质
        map.put("plateSpec", detail.getPlateSpec());//盲板-规格
        map.put("plateCode", detail.getPlateCode());//盲板-编号
        map.put("opDepartCommanderName", detail.getOpDepartCommanderName());//生产单位作业指挥

        //盲板抽堵人
        List<Map<String, String>> peopleMapList = new ArrayList<Map<String, String>>();
        if (CollectionUtils.isEmpty(detail.getPeopleBeans())) {
            for (BpWorkSafetyCertBlindPlatePeopleBean bean : detail.getPeopleBeans()) {
                Map<String, String> maps = new HashMap<String, String>();
                if (bean.getType() == 0) {
                    maps.put("pType", "抽");
                } else if (bean.getType() == 1) {
                    maps.put("pType", "堵");
                }
                maps.put("pName", bean.getPeopleName());//作业人姓名
                maps.put("gName", bean.getGuardianName());//监护人员姓名
                //作业人证书名称
                if (CollectionUtils.isEmpty(bean.getPeopleDto())) {
                    List<String> pcNames = bean.getPeopleDto().stream().map(e -> e.getName()).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(pcNames)) {
                        maps.put("pcNames", Joiner.on(",").join(pcNames));
                    }
                }
                //监护人员证书
                if (CollectionUtils.isEmpty(bean.getGuardianDto())) {
                    List<String> gcNames = bean.getGuardianDto().stream().map(e -> e.getName()).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(gcNames)) {
                        maps.put("gcNames", Joiner.on(",").join(gcNames));
                    }
                }
                peopleMapList.add(maps);
            }
            map.put("p", peopleMapList);
        }

        //共有信息
        Map<String, Object> commonMap = getSafetyCommonContent(map, data);
        //图片
        Map<String, Object> resultMap = getPhoto(commonMap, id);
        return resultMap;
    }

    /**
     * 获取动土打印数据
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getDongTuSafetyMap(Long id) throws IOException {
        BpWorkSafetyCertDetailBean data = this.getById(id);
        Map<String, Object> map = new HashMap<String, Object>();
        BpWorkSafetyCertBreakGroundDetailBean detail = (BpWorkSafetyCertBreakGroundDetailBean) data;
        map.put("workDepartName", detail.getWorkDepartName());//作业单位名称
        //共有信息
        Map<String, Object> commonMap = getSafetyCommonContent(map, data);
        //图片
        Map<String, Object> resultMap = getPhoto(commonMap, id);
        return resultMap;
    }

    /**
     * 获取断路打印数据
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getDuanLuSafetyMap(Long id) throws IOException {
        BpWorkSafetyCertDetailBean data = this.getById(id);
        BpWorkSafetyCertBreakRoadDetailBean detail = (BpWorkSafetyCertBreakRoadDetailBean) data;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("workDepartName", detail.getWorkDepartName());//作业单位
        //断路原因
        if (StringUtils.isNotBlank(detail.getBreakReason())) {
            map.put("breakReason", detail.getBreakReason());
        } else {
            //兼容字段误传
            map.put("breakReason", detail.getWorkContent());
        }
        map.put("breakDescription", detail.getBreakDescription());//断路地段示意图及相关说明
        map.put("otherDepartName", detail.getOtherDepartName());//涉及的相关单位(部门)
        //共有信息
        Map<String, Object> commonMap = getSafetyCommonContent(map, data);
        //图片
        Map<String, Object> resultMap = getPhoto(commonMap, id);
        return resultMap;
    }

    @Override
    public ResultBean workPrescription() {
        List<BpWorkSafetyCert> list = dao.findByStateBetween(SafetyWorkStates.CHECK_ACCEPTED.getId(), SafetyWorkStates.CHECK_FAILED.getId());
        if (CollectionUtils.isEmpty(list)) {
            return ResultBean.success(Lists.newArrayList());
        }
        List<Integer> collect = list.stream().map(r -> getDurationDays(r.getApplyTime(), r.getCheckTime())).collect(Collectors.toList());
        Map<String, Long> map = collect.stream().collect(Collectors.groupingBy((Integer r) -> convertDay(r), Collectors.counting()));
        List<BpWorkStaticsDto> resultList = Lists.newArrayList();
        map.forEach((r, v) -> resultList.add(new BpWorkStaticsDto(r, v.intValue())));
        return ResultBean.success(resultList);
    }

    @Override
    public ResultBean workToday() {
        //取作业开始和结束时间
        List<BpWorkSafetyCert> list = dao.findByTime(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        Map<String, Long> map = new HashMap<>(9);
        if (!CollectionUtils.isEmpty(list)) {
            map = list.stream().collect(Collectors.groupingBy(BpWorkSafetyCert::getType, Collectors.counting()));
        }
        addCert(map);
        return ResultBean.success(covert(map));
    }

    @Override
    public ResultBean workApply() {
        //最近30天 申请单位统计 饼图
        List<BpWorkSafetyCert> list = getRecentNdaysWork(30);
        if (CollectionUtils.isEmpty(list)) {
            return ResultBean.success(null);
        }
        int size = list.size();
        Map<Long, Long> map = list.stream().filter(r -> r.getApplyDepartId() != null).collect(Collectors.groupingBy(BpWorkSafetyCert::getApplyDepartId,
                Collectors.counting()));
        Map<Long, String> toolMap = getToolMap(map.keySet());
        return ResultBean.success(convertToApply(size, map, toolMap));
    }

    @Override
    public ResultBean work30Recent() {
        return ResultBean.success(BpWork30RecentDto.getDto(getNdaysRecent(30)));
    }

    @Override
    public ResultBean workAuditPass() {
        List<BpWorkSafetyCert> certList = getRecentNdaysWork(30);
        long auditFail = certList.stream().filter(r -> r.getState() != null && r.getState() == SafetyWorkStates.AUDIT_FAILED.getId()).count();
        long auditSuccess = certList.stream().filter(r -> r.getState() != null
                && (r.getState() >= SafetyWorkStates.CHECK_ACCEPTED.getId() ||
                r.getState() == SafetyWorkStates.AUDIT_SUCCESS.getId())).count();
        int total = Long.valueOf(auditSuccess + auditFail).intValue();
        List<BpWorkApplyDetailDto> applyDetailList = Lists.newArrayList();
        applyDetailList.add(new BpWorkApplyDetailDto("未通过", (int) auditFail));
        applyDetailList.add(new BpWorkApplyDetailDto("通过", (int) auditSuccess));
        return ResultBean.success(new BpWorkApplyDto(total, applyDetailList));
    }

    @Override
    public ResultBean workCheckPass() {
        RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
        List<String> aList = bean.getInputArguments();

        for (int i = 0; i < aList.size(); i++) {
            System.out.println(aList.get(i));
        }
        List<BpWorkSafetyCert> certList = getRecentNdaysWork(30);
        long checkFail = certList.stream().filter(r -> r.getState() != null && r.getState() == SafetyWorkStates.CHECK_FAILED.getId()).count();
        long checkSuccess = certList.stream().filter(r -> r.getState() != null && r.getState() == SafetyWorkStates.CHECK_ACCEPTED.getId()).count();
        int total = Long.valueOf(checkFail + checkSuccess).intValue();
        List<BpWorkApplyDetailDto> applyDetailList = Lists.newArrayList();
        applyDetailList.add(new BpWorkApplyDetailDto("不合格", (int) checkFail));
        applyDetailList.add(new BpWorkApplyDetailDto("合格", (int) checkSuccess));
        return ResultBean.success(new BpWorkApplyDto(total, applyDetailList));
    }

    /**
     * 最近N天的作业数量统计
     */
    private TreeMap<LocalDate, Integer> getNdaysRecent(int days) {
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(days - 1);
        List<BpWorkSafetyCert> list = getRecentNdaysWork(days - 1);
        Map<LocalDate, Integer> toolMap = getLocalDateMap(startDate, endDate);
        addWorkData(toolMap, list, startDate, endDate);
        TreeMap<LocalDate, Integer> treeMap = new TreeMap<>(toolMap);
        return treeMap;
    }

    /**
     * N天内的作业
     */
    private List<BpWorkSafetyCert> getRecentNdaysWork(int days) {
        LocalDateTime endTime = LocalDateTime.of(LocalDate.now(), LocalTime.of(23, 59, 59));
        LocalDateTime startTime = LocalDateTime.of(LocalDate.now().minusDays(days - 1), LocalTime.of(0, 0, 0));
        List<BpWorkSafetyCert> list = dao.findByStartTimeBetweenOrEndTimeBetween(startTime, endTime);
        return list;
    }

    private void addWorkData(Map<LocalDate, Integer> toolMap, List<BpWorkSafetyCert> list,
                             LocalDate targetStart, LocalDate targetEnd) {
        for (BpWorkSafetyCert cert : list) {
            LocalDateTime startTime = DateTimeUtil.date2LocalDateTime(cert.getStartTime());
            LocalDateTime endTime = DateTimeUtil.date2LocalDateTime(cert.getEndTime());
            LocalDate startDate = startTime.toLocalDate();
            LocalDate endDate = endTime.toLocalDate();
            List<LocalDate> tempList = Lists.newArrayList();
            for (LocalDate temp = startDate; temp.isBefore(endDate.plusDays(1)); temp = temp.plusDays(1)) {
                if (temp.isAfter(targetStart.minusDays(1)) && temp.isBefore(targetEnd.plusDays(1))) {
                    tempList.add(temp);
                }
            }
            for (LocalDate localDate : tempList) {
                Integer i = toolMap.get(localDate);
                toolMap.put(localDate, ++i);
            }
        }
    }


    private Map<LocalDate, Integer> getLocalDateMap(LocalDate startDate, LocalDate endDate) {
        Map<LocalDate, Integer> toolMap = new HashMap<>(30);
        for (LocalDate tempDate = startDate; tempDate.isBefore(endDate.plusDays(1)); tempDate = tempDate.plusDays(1)) {
            toolMap.put(tempDate, 0);
        }
        return toolMap;
    }

    private BpWorkApplyDto convertToApply(int size, Map<Long, Long> map, Map<Long, String> toolMap) {
        List<BpWorkApplyDetailDto> applyDetailList = Lists.newArrayList();
        for (Long aLong : map.keySet()) {
            applyDetailList.add(new BpWorkApplyDetailDto(toolMap.get(aLong), map.get(aLong).intValue()));
        }
        return new BpWorkApplyDto(size, applyDetailList);
    }

    private Map<Long, String> getToolMap(Set<Long> keySet) {
        List<BpDepart> list = bpDepartDao.findAllById(keySet);
        return list.stream().collect(Collectors.toMap(BpDepart::getId, BpDepart::getName));
    }

    private BpWorkTodayDto covert(Map<String, Long> map) {
        List<String> certNameList = map.keySet().stream().map(r -> r + "作业").collect(Collectors.toList());
        List<Integer> sumList = map.values().stream().map(r -> r.intValue()).collect(Collectors.toList());
        return new BpWorkTodayDto(certNameList, sumList);
    }

    private void addCert(Map<String, Long> map) {
        List<String> list = SafetyWorkTypes.getAllName();
        for (String s : list) {
            map.putIfAbsent(s, 0L);
        }
    }

    private String convertDay(Integer day) {
        if (day <= 3) {
            return "1-3天";
        } else if (day <= 6) {
            return "4-6天";
        } else if (day <= 9) {
            return "7-9天";
        } else if (day <= 12) {
            return "10-12天";
        }
        return ">12天";
    }

    private int getDurationDays(Date startTime, Date endTime) {
        if (startTime == null || endTime == null) {
            return 1;
        }
        LocalDateTime start = DateTimeUtil.date2LocalDateTime(startTime);
        LocalDateTime end = DateTimeUtil.date2LocalDateTime(endTime);
        Duration between = Duration.between(start, end);
        Long l = between.toDays();
        return l.intValue() + 1;
    }

    /**
     * 保存作业证安全措施模板
     *
     * @param list
     * @return
     */
    @Override
    public List<BpWorkSafetyMethodConfig> saveMethodTemplate(List<BpWorkSafetyMethodConfigBean> list) {
        List<BpWorkSafetyMethodConfig> configList = new ArrayList<>();
        int index = 1;
        if (!CollectionUtils.isEmpty(list)) {
            for (BpWorkSafetyMethodConfigBean bean : list) {
                BpWorkSafetyMethodConfig config = new BpWorkSafetyMethodConfig();
                if (bean.getId() != null) {
                    //删除
                    if (bean.getFlag() != null && bean.getFlag() == 1) {
                        bpWorkSafetyMethodConfigDao.deleteById(bean.getId());
                        continue;
                    }
                    //修改
                    config = bpWorkSafetyMethodConfigDao.findById(bean.getId()).orElseThrow(() -> new IllegalArgumentException("安全措施模板不存在"));
                }
                BeanUtils.copyProperties(bean, config);
                config.setSerialNumber(index);
                index++;
                BpWorkSafetyMethodConfig save = bpWorkSafetyMethodConfigDao.save(config);
                configList.add(save);
            }
        }
        return configList;
    }

    /**
     * 查看作业证安全措施模板
     *
     * @param type
     * @return
     */
    @Override
    public List<BpWorkSafetyMethodConfigBean> getMethodTemplateList(String type) {
        List<BpWorkSafetyMethodConfig> configList = bpWorkSafetyMethodConfigDao.findByType(type);
        List<BpWorkSafetyMethodConfigBean> beanList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(configList)) {
            for (BpWorkSafetyMethodConfig config : configList) {
                BpWorkSafetyMethodConfigBean bean = new BpWorkSafetyMethodConfigBean();
                BeanUtils.copyProperties(config, bean);
                bean.setType(config.getType());
                beanList.add(bean);
            }
        }
        return beanList;
    }

    /**
     * 删除安全措模板
     *
     * @param id
     */
    @Override
    public void deleteMethodTemplate(Long id) {
        bpWorkSafetyMethodConfigDao.deleteById(id);
    }

    //待办事项获取待审核列表
    @Override
    public ResultBean getWaitForAuditList(Pageable pageable) {
        List<BpWorkSafetyCert> list = bpWorkSafetyCertDao.findByState(1);
        List<BpWorkSafetyCert> alist = new ArrayList();
        List<BpWorkSafetyAppListBean> beanList = new ArrayList();
        if (!CollectionUtils.isEmpty(list)) {
            for (BpWorkSafetyCert cert : list) {
                //审核模板
                List<BpWorkSafetyAuditTemplate> tList = new ArrayList<>();
//                if (cert.getType() != null && cert.getWorkLevel() == null) {
//                    tList = bpWorkSafetyAuditTemplateDao.findByType(cert.getType());
//                    if (CollectionUtils.isEmpty(tList)) {
//                        throw new IllegalArgumentException("当前作业未设置审核流程，请先设置审核流程");
//                    }
//                } else if (cert.getType() != null && cert.getWorkLevel() != null) {
//                    tList = bpWorkSafetyAuditTemplateDao.findByTypeAndWorkLevel(cert.getType(), cert.getWorkLevel());
//                    if (CollectionUtils.isEmpty(tList)) {
//                        throw new IllegalArgumentException("当前作业未设置审核流程，请先设置审核流程");
//                    }
//                }
                //审核流程
                BpWorkSafetyAuditProcess process = bpWorkSafetyAuditProcessDao.findByCertId(cert.getId());
                //第一次审核-从审核模板中取得
                if (process == null) {
                    //目前一个作业证只有一个审核模板
                    BpWorkSafetyAuditProcessAddBean aBean = JSONObject.parseObject(tList.get(0).getProcessJson(),
                            BpWorkSafetyAuditProcessAddBean.class);
                    List<BpWorkSafetyAuditProcessBean> processBeans = aBean.getProcessBeans();
                    if (!CollectionUtils.isEmpty(processBeans)) {

                        //类型是岗位
                        if (processBeans.get(0).getType() == null) {
                            alist.add(cert);
                        } else if (processBeans.get(0).getType() == 0) {
                            if (processBeans.get(0).getPersonOrDepartId().equals(Context.getJobId())) {
                                alist.add(cert);
                            }
                            //类型是人员
                        } else if (processBeans.get(0).getType() == 1) {
                            if (processBeans.get(0).getPersonOrDepartId().equals(Context.getCurrentUserId())) {
                                alist.add(cert);
                            }
                        } else if (processBeans.get(0).getType() == null || processBeans.get(0).getPersonOrDepartId() == null) {
                            alist.add(cert);
                        } else {
                            alist.add(cert);
                        }
                    }
                } else if (process.getNextAuditorId() != null) {
                    if (process.getNextAuditorType() == 0) {
                        if (process.getNextAuditorId().equals(Context.getJobId())) {
                            alist.add(cert);
                        }
                    } else if (process.getNextAuditorType() == 1) {
                        if (process.getNextAuditorId().equals(Context.getCurrentUserId())) {
                            alist.add(cert);
                        }
                    } else {
                        alist.add(cert);
                    }
                }
            }
        }

        if (!CollectionUtils.isEmpty(alist)) {
            for (BpWorkSafetyCert cert : alist) {
                BpWorkSafetyAppListBean bean = new BpWorkSafetyAppListBean();
                bean.setId(cert.getId());
                //类型
                bean.setType(cert.getType() + "安全作业");
                //申请人
                if (cert.getApplyUserId() != null && baseUserDao.findById(cert.getApplyUserId()).isPresent()) {
                    bean.setApplyUserName(baseUserDao.findById(cert.getApplyUserId()).get().getRealName());
                }
                //申请时间
                bean.setApplyTime(cert.getApplyTime());
                //作业时间
                bean.setWorkTime(parseWorkTime(cert));
                //作业类型编码
                bean.setTypeName(SafetyWorkTypes.findByName(cert.getType()).getCode());
                beanList.add(bean);
            }
        }
        List<BpWorkSafetyAppListBean> resultList = beanList.stream().sorted((a, b) -> b.getId().intValue() - a.getId().intValue()).collect(Collectors.toList());
        return getResultBean(pageable, resultList);
    }

    //待办事项获取待验收列表
    @Override
    public ResultBean getWaitForCheckList(Pageable pageable) {
        List<BpWorkSafetyCert> list = bpWorkSafetyCertDao.getCheckSafetys(2, 6);
        List<BpWorkSafetyAppListBean> beanList = new ArrayList();
        if (!CollectionUtils.isEmpty(list)) {
            for (BpWorkSafetyCert cert : list) {
                BpWorkSafetyAppListBean bean = new BpWorkSafetyAppListBean();
                bean.setId(cert.getId());
                //类型
                bean.setType(cert.getType() + "安全作业");
                //申请时间
                bean.setApplyTime(cert.getApplyTime());
                //作业时间
                bean.setWorkTime(parseWorkTime(cert));
                //作业类型编码
                bean.setTypeName(SafetyWorkTypes.findByName(cert.getType()).getCode());
                //申请人
                if (cert.getApplyUserId() != null && baseUserDao.findById(cert.getApplyUserId()).isPresent()) {
                    bean.setApplyUserName(baseUserDao.findById(cert.getApplyUserId()).get().getRealName());
                }
                beanList.add(bean);
            }
        }
        List<BpWorkSafetyAppListBean> resultList = beanList.stream().sorted((a, b) -> b.getId().intValue() - a.getId().intValue()).collect(Collectors.toList());
        return getResultBean(pageable, resultList);
    }

    /**
     * 修改模板状态
     *
     * @param id
     * @param state
     */
    @Override
    public void updateTemplateState(Long id, Integer state) {
        BpWorkSafetyAuditTemplate template = bpWorkSafetyAuditTemplateDao.findById(id).orElseThrow(() -> new IllegalArgumentException("模板不存在"));
        template.setState(state);
        bpWorkSafetyAuditTemplateDao.save(template);
    }

    /**
     * 获取未同步的作业类型
     *
     * @return
     */
    @Override
    public List<BpWorkSafetyCertType> getWorkCertType() {
        List<BpWorkSafetyCertType> al = bpWorkSafetyCertTypeDao.findAll();
        List<BpWorkSafetyCertType> all = bpWorkSafetyCertTypeDao.findBySyncStates(0);
        List<BpWorkSafetyCertType> ala = bpWorkSafetyCertTypeDao.findBySyncState(0);
        //       List<BpWorkSafetyCertTypeBean> list = new ArrayList<>();
//        if (!CollectionUtils.isEmpty(all)) {
//            for (BpWorkSafetyCertType type : all) {
//                BpWorkSafetyCertTypeBean bean = new BpWorkSafetyCertTypeBean();
//                BeanUtils.copyProperties(type, bean);
//                if (type.getSyncState() == 0) {
//                    bean.setSyncStateName("未同步");
//                } else if (type.getSyncState() == 1) {
//                    bean.setSyncStateName("已同步");
//                }
//                if (type.getWorkLevel() != null) {
//                    bean.setWorkLevelName(WorkLevels.findNameById(type.getWorkLevel()));
//                    if (type.getName().equals("动火") && type.getWorkLevel() == 0) {
//                        bean.setWorkLevelName("特殊危险");
//                    }
//                }
//                type.setSyncState(1);
//                bpWorkSafetyCertTypeDao.save(type);
//                list.add(bean);
//            }
//        }
        return all;
    }

    /**
     * 获取作业证类型列表
     */

    @Override
    public List<SimpleSelectListBean> getSafetyTypeList() {
        List<SimpleSelectListBean> list = new ArrayList<>();
        for (int i = 1; i < 10; i++) {
            SimpleSelectListBean bean = new SimpleSelectListBean();
            bean.setValue(new Long((long) i));
            bean.setLabel(SafetyWorkTypes.findNameById(i));
            list.add(bean);
        }
        return list;
    }

    /**
     * 获取作业证类型
     */
    @Override
    public List<SimpleSelectListBean> getSafetyStateList() {
        List<SimpleSelectListBean> list = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            SimpleSelectListBean bean = new SimpleSelectListBean();
            bean.setValue(new Long((long) i));
            bean.setLabel(SafetyWorkStates.findNameById(i));
            list.add(bean);
        }
        return list;
    }

    /**
     * 获取其他特殊作业证列表
     */
    @Override
    public Page<BpOtherSafetyWorkSearchBean> getOtherSafetyWorkList(Pageable page, OtherSafetyWorkSearchBean condition) {
        page = PageDataUtils.addOrderByDesc(page, "id");
        Predicate predicate = prepareOtherSafetyWorkListSearchCondition(condition);
        Page<BpWorkSafetyCert> data = predicate == null ? dao.findAll(page) : dao.findAll(predicate, page);
        return PageDataUtils.convertPageData(data,
                new PageDataConvert<BpOtherSafetyWorkSearchBean, BpWorkSafetyCert>() {
                    @Override
                    public BpOtherSafetyWorkSearchBean convert(BpWorkSafetyCert f) {
                        BpWorkSafetyPeopleTypeBean peopleTypeBean = null;
                        if (StringUtils.isNotBlank(f.getPeopleTypeJson())) {
                            peopleTypeBean = JSONObject.parseObject(f.getPeopleTypeJson(), BpWorkSafetyPeopleTypeBean.class);
                        }
                        BpOtherSafetyWorkSearchBean bean = new BpOtherSafetyWorkSearchBean();
                        // ID
                        bean.setId(f.getId());
                        bean.setName(f.getType() + "(" + f.getCode() + ")");
                        if (f.getApplyUserId() != null) {
                            if (peopleTypeBean == null) {
                                bean.setApplyPeopleName(getName(baseUserDao.getBaseUserNameById(f.getApplyUserId()), getCertNames(f.getApplyUserCertIdJson())));

                            } else if (peopleTypeBean.getApplyUserType() != null && peopleTypeBean.getApplyUserType() == 1) {
                                bean.setApplyPeopleName(getName(bpContractorStaffService.getNameById(f.getApplyUserId()), getCertNames(f.getApplyUserCertIdJson())));
                            } else {
                                bean.setApplyPeopleName(getName(baseUserDao.getBaseUserNameById(f.getApplyUserId()), getCertNames(f.getApplyUserCertIdJson())));
                            }
                        }
                        bean.setAppleTime(f.getApplyTime());
                        //类型编号,用于跳转
                        bean.setType(f.getType());
                        if (SafetyWorkTypes.findByName(f.getType()) != null) {
                            bean.setTypeCode(SafetyWorkTypes.findByName(f.getType()).getCode());
                        }
                        return bean;
                    }
                });
    }

    /**
     * 作业统计
     *
     * @param page
     * @param condition
     * @return
     */
    @Override
    public ResultBean safetyStatistics(Pageable page, BpSafetyStatisticsSearchBean condition) {
        page = PageDataUtils.addOrderByDesc(page, "id");
        Predicate predicate = prepareSafetyStatisticsSearch(condition);
        Page<BpWorkSafetyCert> data = predicate == null ? dao.findAll(page) : dao.findAll(predicate, page);
        Page<BpSafetyStatisticsBean> p = PageDataUtils.convertPageData(data,
                new PageDataConvert<BpSafetyStatisticsBean, BpWorkSafetyCert>() {
                    @Override
                    public BpSafetyStatisticsBean convert(BpWorkSafetyCert f) {
                        BpWorkSafetyPeopleTypeBean peopleTypeBean = null;
                        if (StringUtils.isNotBlank(f.getPeopleTypeJson())) {
                            peopleTypeBean = JSONObject.parseObject(f.getPeopleTypeJson(), BpWorkSafetyPeopleTypeBean.class);
                        }
                        BpSafetyStatisticsBean bean = new BpSafetyStatisticsBean();
                        // id
                        bean.setId(f.getId());
                        //编号
                        bean.setCode(f.getCode());
                        //类型
                        bean.setTypeName(f.getType());
                        if (SafetyWorkTypes.findByName(f.getType()) != null) {
                            //类型编号
                            bean.setTypeCode(SafetyWorkTypes.findByName(f.getType()).getCode());
                        }
                        //作业级别
                        bean.setWorkLevelName(WorkLevels.findNameById(f.getWorkLevel()));
                        if ("动火".equals(f.getType()) && f.getWorkLevel() == 0) {
                            bean.setWorkLevelName("特殊危险");
                        }
                        //作业内容
                        bean.setWorkContent(f.getWorkContent());
                        //申请人姓名
                        if (f.getApplyUserId() != null) {
                            if (peopleTypeBean == null) {
                                bean.setApplyPeopleName(getName(baseUserDao.getBaseUserNameById(f.getApplyUserId()), getCertNames(f.getApplyUserCertIdJson())));

                            } else if (peopleTypeBean.getApplyUserType() != null && peopleTypeBean.getApplyUserType() == 1) {
                                bean.setApplyPeopleName(getName(bpContractorStaffService.getNameById(f.getApplyUserId()), getCertNames(f.getApplyUserCertIdJson())));
                            } else {
                                bean.setApplyPeopleName(getName(baseUserDao.getBaseUserNameById(f.getApplyUserId()), getCertNames(f.getApplyUserCertIdJson())));
                            }
                        }
                        //所属风险区域
                        if (f.getRiskDistrictId() != null) {
                            bean.setRiskDistrictName(riskDistrictDao.findNameById(f.getRiskDistrictId()));
                        }
                        //作业时间
                        bean.setWorkTime(parseWorkTime(f));
                        //申请时间
                        bean.setApplyTime(f.getApplyTime());
                        //申请单位
                        if (f.getApplyDepartId() != null) {
                            bean.setApplyDepartName(bpDepartDao.getNameById(f.getApplyDepartId()));
                        }
                        //状态名称
                        bean.setStateName(SafetyWorkStates.findNameById(f.getState()));
                        //是否需要用电申请签章
                        if (StringUtils.isNotBlank(f.getNeedEletricityApplySheet())) {
                            if (f.getNeedEletricityApplySheet().equals("Y")) {
                                bean.setNeedEletricityApplySheet("是");
                            } else if (f.getNeedEletricityApplySheet().equals("N")) {
                                bean.setNeedEletricityApplySheet("否");
                            }
                        }
                        String monitorUserName = null;
                        // 监护人
                        if (f.getType().equals(SafetyWorkTypes.MANG_BAN_CHOU_DU.getName())) {
                            BpWorkSafetyCertDetailBean bbd = getById(f.getId());
                            BpWorkSafetyCertBlindPlateDetailBean detail = (BpWorkSafetyCertBlindPlateDetailBean) bbd;
                            if (StringUtils.isNotBlank(detail.getPumpMonitorUserName())) {
                                monitorUserName = detail.getPumpMonitorUserName() + "(抽)";
                            }
                            if (StringUtils.isNotBlank(detail.getBlockMonitorUserName())) {
                                monitorUserName = detail.getBlockMonitorUserName() + "(堵)";
                            }
                            if (StringUtils.isNotBlank(detail.getPumpMonitorUserName()) && StringUtils.isNotBlank(detail.getBlockMonitorUserName())) {
                                monitorUserName = detail.getPumpMonitorUserName() + "(抽)|" + detail.getBlockMonitorUserName() + "(堵)";
                            }
                        } else {
                            if (StringUtils.isNotBlank(f.getMonitorUserCode())) {
                                if (peopleTypeBean == null) {
                                    monitorUserName = getName(findUserNameByCode(f.getMonitorUserCode()), getCertNames(f.getMonitorUserCertIdJson()));
                                } else if (peopleTypeBean.getOpMonitorUserType() != null && peopleTypeBean.getOpMonitorUserType() == 1) {
                                    monitorUserName = getName(bpContractorStaffService.getNameById(parseLong(f.getMonitorUserCode())), getCertNames(f.getMonitorUserCertIdJson()));
                                } else {
                                    monitorUserName = getName(findUserNameByCode(f.getMonitorUserCode()), getCertNames(f.getMonitorUserCertIdJson()));
                                }
                            }
                        }
                        bean.setMonitorUserName(monitorUserName);
                        return bean;
                    }
                });
        return ResultBean.pageData(p.getContent(), p.getTotalElements());
    }

    private Predicate prepareSafetyStatisticsSearch(BpSafetyStatisticsSearchBean condition) {
        QBpWorkSafetyCert cert = QBpWorkSafetyCert.bpWorkSafetyCert;
        Predicate p = null;
        //作业编号或申请人姓名
        if (condition.getCodeOrApplyUserName() != null) {
            p = ExpressionUtils.and(p, ExpressionUtils.or(cert.code.contains(condition.getCodeOrApplyUserName()),
                    cert.applyUserId.in(getApplypeopleIdList(condition.getCodeOrApplyUserName()))));
        }
        //作业类型id
        if (condition.getTypeId() != null) {
            p = ExpressionUtils.and(p, cert.type.eq(SafetyWorkTypes.findNameById(condition.getTypeId())));
        }
        //所属风险区域id
        if (condition.getRiskDistrictId() != null) {
            p = ExpressionUtils.and(p, cert.riskDistrictId.eq(condition.getRiskDistrictId()));
        }
        //申请单位
        if (condition.getApplyDepartId() != null) {
            p = ExpressionUtils.and(p, cert.applyDepartId.eq(condition.getApplyDepartId()));
        }
        //申请日期
        if (condition.getApplyTime() != null) {
            LocalDateTime startTime = LocalDateTime.of(DateTimeUtil.date2LocalDate(condition.getApplyTime()), LocalTime.of(0, 0, 0));
            LocalDateTime endTime = LocalDateTime.of(DateTimeUtil.date2LocalDate(condition.getApplyTime()), LocalTime.of(23, 59, 59));
            p = ExpressionUtils.and(p, cert.applyTime.between(DateTimeUtil.localDateTime2Date(startTime), DateTimeUtil.localDateTime2Date(endTime)));
        }
        //作业时间
        if (condition.getStartTime() != null && condition.getEndTime() != null) {
            LocalDateTime startTime = LocalDateTime.of(DateTimeUtil.date2LocalDate(condition.getStartTime()), LocalTime.of(0, 0, 0));
            LocalDateTime endTime = LocalDateTime.of(DateTimeUtil.date2LocalDate(condition.getEndTime()), LocalTime.of(23, 59, 59));
//            p = ExpressionUtils.and(p, ExpressionUtils.or(cert.startTime.after(DateTimeUtil.localDateTime2Date(startTime)), cert.startTime.eq(DateTimeUtil.localDateTime2Date(startTime))));
//            p = ExpressionUtils.and(p, ExpressionUtils.or(cert.endTime.before(DateTimeUtil.localDateTime2Date(endTime)), cert.endTime.eq(DateTimeUtil.localDateTime2Date(endTime))));
            p = ExpressionUtils.and(p, cert.startTime.between(DateTimeUtil.localDateTime2Date(startTime), DateTimeUtil.localDateTime2Date(endTime)));
            p = ExpressionUtils.and(p, cert.endTime.between(DateTimeUtil.localDateTime2Date(startTime), DateTimeUtil.localDateTime2Date(endTime)));
        }
        //状态
        if (condition.getState() != null) {
            p = ExpressionUtils.and(p, cert.state.eq(condition.getState()));
        }
        //是否需要临时用电
        if (StringUtils.isNotBlank(condition.getNeedEletricityApplySheet())) {
            p = ExpressionUtils.and(p, cert.needEletricityApplySheet.eq(condition.getNeedEletricityApplySheet()));
        }
        return p;
    }

    private Predicate prepareOtherSafetyWorkListSearchCondition(OtherSafetyWorkSearchBean condition) {
        QBpWorkSafetyCert cert = QBpWorkSafetyCert.bpWorkSafetyCert;
        Predicate p = null;
        if (condition.getSafetyType() != null) {
            p = ExpressionUtils.and(p, cert.type.eq(SafetyWorkTypes.findNameById(condition.getSafetyType())));
        }
        if (condition.getApplyTime() != null) {
            LocalDateTime startTime = LocalDateTime.of(DateTimeUtil.date2LocalDate(condition.getApplyTime()), LocalTime.of(0, 0, 0));
            LocalDateTime endTime = LocalDateTime.of(DateTimeUtil.date2LocalDate(condition.getApplyTime()), LocalTime.of(23, 59, 59));
            p = ExpressionUtils.and(p, cert.applyTime.between(DateTimeUtil.localDateTime2Date(startTime), DateTimeUtil.localDateTime2Date(endTime)));
        }
        if (condition.getPeopleNameOrSafetyCode() != null) {
            p = ExpressionUtils.and(p, ExpressionUtils.or(cert.code.contains(condition.getPeopleNameOrSafetyCode()),
                    cert.applyUserId.in(getApplypeopleIdList(condition.getPeopleNameOrSafetyCode()))));
        }
        return p;
    }

    private List<Long> getApplypeopleIdList(String name) {
        List<Long> list = new ArrayList<>();
        if (StringUtils.isNotBlank(name)) {
            List<Long> uList = baseUserDao.getUserIdByNameContains(name);
            List<Long> cuList = bpContractorStaffDao.getUserIdByNameContains(name);
            list.addAll(uList);
            list.addAll(cuList);
        }
        return list;
    }

    @Override
    public ResultBean workRisk() {
        //最近30天 风险统计 饼图
        List<BpWorkSafetyCert> list = getRecentNdaysWork(30);
        if (CollectionUtils.isEmpty(list)) {
            return ResultBean.success(BpWorkRiskDto.defaultDto());
        }
        Map<Integer, Long> map = list.parallelStream().map(r -> {
            Long riskDistrictId = r.getRiskDistrictId();
            Long riskPointId = r.getRiskPointId();
            List<Integer> temp = Lists.newArrayList();
            if (riskDistrictId != null) {
                riskDistrictDao.findById(riskDistrictId).ifPresent(v -> temp.add(v.getRiskLevel()));
            }
            if (riskPointId != null) {
                riskPointDao.findById(riskPointId).ifPresent(v -> {
                    Integer riskLevel = v.getRiskLevel();
                    if (riskLevel != null) {
                        if (temp.size() > 0) {
                            Integer integer = temp.get(0);
                            if ((integer != null && integer > riskLevel) || integer == null) {
                                temp.add(0, riskLevel);
                            }
                        } else {
                            temp.add(riskLevel);
                        }
                    }
                });
            }
            return temp.size() == 0 ? null : temp.get(0);
        }).filter(Objects::nonNull).collect(Collectors.groupingBy(r -> r.intValue(), Collectors.counting()));
        for (int i = 1; i <= 4; i++) {
            map.putIfAbsent(i, 0L);
        }
        List<BpWorkRiskDto> dtoList = Lists.newArrayList();
        for (Integer integer : map.keySet()) {
            dtoList.add(new BpWorkRiskDto(RiskLevels.findRiskLevelName(integer), map.get(integer).intValue()));
        }
        return ResultBean.success(dtoList);
    }

    @Override
    public ResultBean workArea() {
        //最近30天 区域统计 饼图
        List<BpWorkSafetyCert> list = getRecentNdaysWork(30);
        if (CollectionUtils.isEmpty(list)) {
            return ResultBean.success(null);
        }
        List<Long> collect = list.stream().map(r -> r.getRiskDistrictId()).collect(Collectors.toList());
        Map<Long, Long> map = collect.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(r -> r.longValue(), Collectors.counting()));
        List<RiskDistrict> districtList = riskDistrictDao.findAllById(map.keySet());
        Map<Long, String> toolMap = districtList.stream().collect(Collectors.toMap(RiskDistrict::getId, RiskDistrict::getName));
        List<BpWorkRiskDto> dtoList = Lists.newArrayList();
        for (Long aLong : map.keySet()) {
            dtoList.add(new BpWorkRiskDto(toolMap.get(aLong), map.get(aLong).intValue()));
        }
        return ResultBean.success(dtoList);
    }

    @Override
    public ResultBean workTimeScope() {
        List<BpWorkSafetyCert> list = dao.findAll();
        Map<LocalTime, Integer> timeMap = getTimeMap();
        for (BpWorkSafetyCert cert : list) {
            LocalDateTime startTime = DateTimeUtil.date2LocalDateTime(cert.getStartTime());
            LocalDateTime endTime = DateTimeUtil.date2LocalDateTime(cert.getEndTime());
            //时间相同，只有
            if (startTime.equals(endTime) && startTime.getMinute() == 0) {
                LocalTime time = LocalTime.of(startTime.getHour(), 0, 0);
                timeMap.put(time, timeMap.get(time) + 1);
            } else {
                //todo
            }
        }
        return null;
    }

    private Map<LocalTime, Integer> getTimeMap() {
        Map<LocalTime, Integer> map = new HashMap<>();
        for (int i = 0; i < 13; i++) {
            map.put(LocalTime.of(2 * i, 0, 0), 0);
        }
        return map;
    }

    //SimpleDateFormatCache.getYmd().format(one.getApplyTime())
    //获取作业证word打印共有信息
    private Map<String, Object> getSafetyCommonContent(Map<String, Object> map, BpWorkSafetyCertDetailBean data) {
        map.put("applyDepartName", data.getApplyDepartName());//申请单位
        map.put("applyUserName", data.getApplyUserName());//申请人
        map.put("workLevel", data.getWorkLevelName());//作业级别
        if (data.getApplyTime() != null) {
            map.put("applyTime", SimpleDateFormatCache.getYmdZC().format(data.getApplyTime()));//申请时间
        }
        map.put("code", data.getCode());//作业证编号
        map.put("stateName", data.getStateName());//状态
        map.put("locationCoords", data.getLocationCoords());//作业区域
        if (data.getStartTime() != null) {
            map.put("startTime", SimpleDateFormatCache.getYmdhm().format(data.getStartTime()));//作业开始时间
        }
        if (data.getEndTime() != null) {
            map.put("endTime", SimpleDateFormatCache.getYmdhm().format(data.getEndTime()));//作业结束时间
        }
        map.put("workContent", data.getWorkContent());//作业内容;动土作业范围
        map.put("riskDistrictName", data.getRiskDistrictName());//所属风险区域
        map.put("username", data.getRiskDistrictName());//风险点
        map.put("opUserName", data.getEducationUserName());//实施安全教育人
        map.put("riskLevelName", data.getRiskLevel());//作业风险评估
        map.put("dangerRecoganize", data.getDangerRecoganize());//危害辨识
        map.put("needEletricityApplySheet", data.getNeedEletricityApplySheet());//是否需要电子申请单
        map.put("workToolName", data.getWorkToolName());//工具名称
        map.put("confirmUserName", data.getSafetyMethods().get(0).getConfirmUserName());//确定人
        map.put("editUserName", data.getEditUserName());//编制人
        map.put("monitorUserName", data.getMonitorUserName());//监护人
        map.put("jobSite", data.getJobSite());//动火地点
        if (data.getAttachment() != null) {
            map.put("attachment", data.getAttachment().getName());//附件
        }
        map.put("checkMsg", data.getCheckMsg());//验收消息
        //涉及的其他特殊作业证
        if (!CollectionUtils.isEmpty(data.getBpOtherSpecialWorkBeans())) {
            StringBuilder sb = new StringBuilder();
            for (BpOtherSpecialWorkBean workBean : data.getBpOtherSpecialWorkBeans()) {
                sb.append(workBean.getOtherSpecialWorkName()).append(",");
            }
            map.put("otherSpecialWorkName", sb.deleteCharAt(sb.length() - 1));
        } else {
            map.put("otherSpecialWorkName", "无");
        }
//        if (data.getOtherSpecialWorkId() != null) {
//            SafetyWorkTypes safetyWorkTypes = SafetyWorkTypes.findById(data.getOtherSpecialWorkId().intValue());
//            //涉及的其他特殊作业名称
//            map.put("otherSpecialWorkName", safetyWorkTypes.getName());
//            //编号
//            map.put("otherSpecialWorkCode", safetyWorkTypes.getCode());
//        }

        List<Map<String, String>> listMap = new ArrayList<Map<String, String>>();
        List<Map<String, String>> methodListMap = new ArrayList<Map<String, String>>();
        //操作人
        if (!CollectionUtils.isEmpty(data.getPeople())) {
            List<BpWorkSafetyApplyUserDetailBean> people = data.getPeople();
            for (BpWorkSafetyApplyUserDetailBean person : people) {
                Map<String, String> maps = new HashMap<String, String>();
                maps.put("id", person.getId());//序号
                maps.put("opUserName", person.getOpUserName());//人员
                maps.put("userType", person.getUserType());//身份
                maps.put("departName", person.getDepartName());//所属单位
                maps.put("certName", Joiner.on(",").join(getCertNameList(person.getCertNames())));//证书名称
                listMap.add(maps);
            }
            map.put("m", listMap);
        }
        //安全措施
        if (!CollectionUtils.isEmpty(data.getSafetyMethods())) {
            List<BpWorkSafetyApplyMethodEditBean> methods = data.getSafetyMethods();
            int index = 1;
            for (BpWorkSafetyApplyMethodEditBean methodBean : methods) {
                Map<String, String> maps = new HashMap<String, String>();
                //序号
                map.put("index", String.valueOf(index));
                //措施
                map.put("method" + index, methodBean.getMethod());
                //状态名称
                map.put("stateName" + index, methodBean.getStateName());
                //确认人
                if (StringUtils.isNotBlank(methodBean.getConfirmUserName())) {
                    map.put("confirmUserName" + index, methodBean.getConfirmUserName());
                }
                //图片
                Optional<BpWorkSafetyCertMethod> byId = bpWorkSafetyCertMethodDao.findById(methodBean.getId());
                if (byId.isPresent() && byId.get().getSingerId() != null) {
                    Optional<BpWorkSafetySigener> sigenerOp = bpWorkSafetySigenerDao.findById(byId.get().getSingerId());
                    if (sigenerOp.isPresent()) {
                        BpWorkSafetySigener sigener = sigenerOp.get();
                        if (StringUtils.isNotBlank(sigener.getSignerJson())) {
                            BpWorkSafetySigenerListBean listBean = JSONObject.parseObject(sigener.getSignerJson(), BpWorkSafetySigenerListBean.class);
                            if (listBean != null) {
                                List<BpWorkSafetySigenerJsonBean> jsonBeans = listBean.getJsonBeans();
                                if (!org.springframework.util.CollectionUtils.isEmpty(jsonBeans)) {
                                    //图片
                                    if (jsonBeans.get(0).getBaseAttachmentBean() != null) {
                                        Long imageId = jsonBeans.get(0).getBaseAttachmentBean().getId();
                                        BaseImageRepository image = baseImageRespositoryDao.findById(imageId).orElseThrow(() -> new IllegalArgumentException("图片不存在"));
                                        String url = "/home/seekcy/wwyt/wwyt-server/upload/images/" + image.getThumbnailPath();
                                        ImageEntity test = new ImageEntity(url, 50, 50);
                                        test.setType(ImageEntity.URL);
                                        map.put("confirmUserName" + index, test);//图片
                                    }
                                }
                            }
                        }
                    }

                }
                methodListMap.add(maps);
                index++;
            }
            map.put("s", methodListMap);
        }
        return map;
    }

    //获取作业证word打印图片信息
    private Map<String, Object> getPhoto(Map<String, Object> map, Long id) throws IOException {
        //图片
        BpWorkSafetyAppAuditBean auditBean = this.getAppCheckById(id);
        if (auditBean != null) {
            List<Map<String, ImageEntity>> currentPhotoList = new ArrayList<Map<String, ImageEntity>>();
            int num = 1;
            List<BpWorkSafetySigenerAddBean> signerBeans = auditBean.getSignerBeans();
            if (!CollectionUtils.isEmpty(signerBeans)) {
                for (BpWorkSafetySigenerAddBean bean : signerBeans) {
                    if (bean.getContent().equals("作业单位负责人意见") || bean.getContent().equals("作业单位意见")) {
                        map.put("sUnitLeaderOpinion", bean.getYesOrNoName());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("sUnitLeaderDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@sUnitLeaderImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("作业单位负责人")) {
                        map.put("zydwfzrOpinion", bean.getYesOrNoName());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("zydwfzrDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@zydwfzrImage", imageEntity);//图片
                        }

                    } else if (bean.getContent().equals("生产单位作业指挥")) {
                        map.put("scdwzyzhOpinion", bean.getYesOrNoName());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("scdwzyzhDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@scdwzyzhImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("作业单位安全部门负责人")) {
                        map.put("zyaqbmOpinion", bean.getYesOrNoName());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("zyaqbmDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@zyaqbmImage", imageEntity);//图片

                        }
                    } else if (bean.getContent().equals("申请单位意见")) {
                        map.put("adOpinion", bean.getYesOrNoName());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("adDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@adImage", imageEntity);//图片

                        }
                    } else if (bean.getContent().equals("审批单位负责人意见")) {
                        map.put("cUnitLeaderOpinion", bean.getYesOrNoName());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("cUnitLeaderDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@cUnitLeaderImage", imageEntity);//图片

                        }
                    } else if (bean.getContent().equals("安全交底人")) {
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("safetyAcceptDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@safetyAcceptImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("接受交底人")) {
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("acceptDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@acceptImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("配送电单位负责人意见")) {
                        map.put("psdOpinion", bean.getYesOrNoName());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("psdDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@psdImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("审批部门负责人意见") || bean.getContent().equals("审批部门意见") || bean.getContent().equals("动火审批人意见")) {
                        map.put("spbmOpinion", bean.getYesOrNoName());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("spbmDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@spbmImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("审批部门(安全/消防部门)负责人意见") || bean.getContent().equals("审批部门（安全/消防部门）负责人意见")) {
                        map.put("spaqOpinion", bean.getYesOrNoName());//意见
                        if (bean.getListBean() != null) {
                            List<BpWorkSafetySigenerJsonBean> jsonBeans = bean.getListBean().getJsonBeans();
                            if (!CollectionUtils.isEmpty(jsonBeans)) {
                                int a = 1;
                                for (BpWorkSafetySigenerJsonBean jsonBean : jsonBeans) {
                                    if (jsonBean != null) {
                                        map.put("spaqDate", getDate(jsonBean.getDate()));//日期
                                        if (jsonBean.getBaseAttachmentBean() != null) {
                                            Long imageId = jsonBean.getBaseAttachmentBean().getId();
                                            BaseImageRepository image = baseImageRespositoryDao.findById(imageId).orElseThrow(() -> new IllegalArgumentException("图片不存在"));
                                            String url = "/home/seekcy/wwyt/wwyt-server/upload/images/" + image.getThumbnailPath();
                                            ImageEntity test = new ImageEntity(url, 50, 50);
                                            test.setType(ImageEntity.URL);
                                            map.put("spaqImage" + a, test);//图片
                                            a++;
                                        }
                                    }
                                }
                            }
                        }
                    } else if (bean.getContent().equals("完工验收")) {
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("checkDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@checkImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("生产车间(分厂)意见") ||
                            bean.getContent().equals("生产车间（分厂）意见") ||
                            bean.getContent().equals("生产车间(分厂)负责人") ||
                            bean.getContent().equals("生产车间（分厂）负责人") ||
                            bean.getContent().equals("车间(分厂)负责人意见") ||
                            bean.getContent().equals("车间（分厂）负责人意见") ||
                            bean.getContent().equals("动火点车间负责人") ||
                            bean.getContent().equals("生产车间(分厂)负责人意见") ||
                            bean.getContent().equals("生产车间（分厂）负责人意见") ||
                            bean.getContent().equals("生产单位负责人") ||
                            bean.getContent().equals("生产单位作业负责人意见")) {
                        map.put("sccjOpinion", bean.getYesOrNoName());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("sccjDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@sccjImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("验收部门负责人意见") || bean.getContent().equals("审核部门负责人意见")) {
                        map.put("ysbmOpinion", bean.getYesOrNoName());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("ysbmDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@ysbmImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("生产单位安全部门负责人") || bean.getContent().equals("安全管理部门意见")) {
                        map.put("scdwaqOpinion", bean.getYesOrNoName());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("scdwaqDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@scdwaqImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("作业单位负责人完工确认情况")) {
                        map.put("dwwgOpinion", bean.getUnitOpinion());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("dwwgDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@dwwgImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("生产车间(分厂)负责人完工确认情况") ||
                            bean.getContent().equals("生产车间（分厂）负责人完工确认情况")) {
                        map.put("cjwgOpinion", bean.getWorkshopOpinion());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("cjwgDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@cjwgImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("有关水、电、工艺、设备、消防、安全等部门负责人意见")) {
                        map.put("manyOpinion", bean.getYesOrNoName());//意见
                        if (bean.getListBean() != null) {
                            List<BpWorkSafetySigenerJsonBean> jsonBeans = bean.getListBean().getJsonBeans();
                            if (!CollectionUtils.isEmpty(jsonBeans)) {
                                int a = 1;
                                for (BpWorkSafetySigenerJsonBean jsonBean : jsonBeans) {
                                    if (jsonBean != null) {
                                        map.put("manyDate", getDate(jsonBean.getDate()));//日期
                                        if (jsonBean.getBaseAttachmentBean() != null) {
                                            Long imageId = jsonBean.getBaseAttachmentBean().getId();
                                            BaseImageRepository image = baseImageRespositoryDao.findById(imageId).orElseThrow(() -> new IllegalArgumentException("图片不存在"));
                                            String url = "/home/seekcy/wwyt/wwyt-server/upload/images/" + image.getThumbnailPath();
                                            ImageEntity test = new ImageEntity(url, 50, 50);
                                            test.setType(ImageEntity.URL);
                                            map.put("manyImage" + a, test);//图片
                                            a++;
                                        }
                                    }
                                }
                            }
                        }

                    } else if (bean.getContent().contains("现场记录")) {
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            Map<String, ImageEntity> maps = new HashMap<String, ImageEntity>();
                            maps.put("@currentImage", imageEntity);
                            currentPhotoList.add(maps);
                            num++;
                        }
                    } else if (bean.getContent().equals("当班班长验票")) {
                        map.put("bzOpinion", bean.getYesOrNoName());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("bzDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@bzImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("编制人")) {
                        map.put("editOpinion", bean.getYesOrNoName());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("editDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@editImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("监护人") || bean.getContent().equals("监火人")) {
                        map.put("monitorOpinion", bean.getYesOrNoName());//意见
                        if (bean.getListBean() != null) {
                            List<BpWorkSafetySigenerJsonBean> jsonBeans = bean.getListBean().getJsonBeans();
                            if (!CollectionUtils.isEmpty(jsonBeans)) {
                                int a = 1;
                                for (BpWorkSafetySigenerJsonBean jsonBean : jsonBeans) {
                                    if (jsonBean != null) {
                                        map.put("monitorDate", getDate(jsonBean.getDate()));//日期
                                        if (jsonBean.getBaseAttachmentBean() != null) {
                                            Long imageId = jsonBean.getBaseAttachmentBean().getId();
                                            BaseImageRepository image = baseImageRespositoryDao.findById(imageId).orElseThrow(() -> new IllegalArgumentException("图片不存在"));
                                            String url = "/home/seekcy/wwyt/wwyt-server/upload/images/" + image.getThumbnailPath();
                                            ImageEntity test = new ImageEntity(url, 50, 50);
                                            test.setType(ImageEntity.URL);
                                            map.put("monitorImage" + a, test);//图片
                                            a++;
                                        }
                                    }
                                }
                            }
                        }
                    } else if (bean.getContent().equals("作业人") || bean.getContent().equals("动火作业人")) {
                        map.put("zyOpinion", bean.getYesOrNoName());//意见
                        if (bean.getListBean() != null) {
                            List<BpWorkSafetySigenerJsonBean> jsonBeans = bean.getListBean().getJsonBeans();
                            if (!CollectionUtils.isEmpty(jsonBeans)) {
                                int a = 1;
                                for (BpWorkSafetySigenerJsonBean jsonBean : jsonBeans) {
                                    if (jsonBean != null) {
                                        map.put("zyDate", getDate(jsonBean.getDate()));//日期
                                        if (jsonBean.getBaseAttachmentBean() != null) {
                                            Long imageId = jsonBean.getBaseAttachmentBean().getId();
                                            BaseImageRepository image = baseImageRespositoryDao.findById(imageId).orElseThrow(() -> new IllegalArgumentException("图片不存在"));
                                            String url = "/home/seekcy/wwyt/wwyt-server/upload/images/" + image.getThumbnailPath();
                                            ImageEntity test = new ImageEntity(url, 50, 50);
                                            test.setType(ImageEntity.URL);
                                            map.put("zyImage" + a, test);//图片
                                            a++;
                                        }
                                    }
                                }
                            }
                        }
                    } else if (bean.getContent().equals("动火措施初审人")) {
                        map.put("opMonitorOpinion", bean.getYesOrNoName());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("opMonitorDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@opMonitorImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("动火作业负责人")) {
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@responsibleUserImage", imageEntity);//图片
                        }
                    }
//                    else if (bean.getContent().equals("实施安全教育人")) {
//                        map.put("eduOpinion", bean.getYesOrNoName());//意见
//                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
//                        map.put("eduDate", getDate(messageBean.getDate()));//日期
//                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
//                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
//                            byte[] abc = ByteStreams.toByteArray(fis);
//                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
//                            map.put("@eduImage", imageEntity);//图片
//                        }
//                    }
                    else if (bean.getContent().equals("实施安全教育人")) {
                        map.put("eduOpinion", bean.getYesOrNoName());//意见
                        if (bean.getListBean() != null) {
                            List<BpWorkSafetySigenerJsonBean> jsonBeans = bean.getListBean().getJsonBeans();
                            if (!CollectionUtils.isEmpty(jsonBeans)) {
                                int a = 1;
                                for (BpWorkSafetySigenerJsonBean jsonBean : jsonBeans) {
                                    if (jsonBean != null) {
                                        map.put("eduDate", getDate(jsonBean.getDate()));//日期
                                        if (jsonBean.getBaseAttachmentBean() != null) {
                                            Long imageId = jsonBean.getBaseAttachmentBean().getId();
                                            BaseImageRepository image = baseImageRespositoryDao.findById(imageId).orElseThrow(() -> new IllegalArgumentException("图片不存在"));
                                            String url = "/home/seekcy/wwyt/wwyt-server/upload/images/" + image.getThumbnailPath();
                                            ImageEntity test = new ImageEntity(url, 50, 50);
                                            test.setType(ImageEntity.URL);
                                            map.put("eduImage" + a, test);//图片
                                            a++;
                                        }
                                    }
                                }
                            }
                        }
                    } else if (bean.getContent().equals("接受安全教育人")) {
                        map.put("accEduOpinion", bean.getYesOrNoName());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("accEduDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@accEduImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("监护人(抽)") ||
                            bean.getContent().equals("监护人（抽）")) {
                        map.put("takMonitorOpinion", bean.getYesOrNoName());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("takMonitorDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@takMonitorImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("监护人(堵)") ||
                            bean.getContent().equals("监护人（堵）")) {
                        map.put("blockMonitorOpinion", bean.getYesOrNoName());//意见
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        map.put("blockMonitorDate", getDate(messageBean.getDate()));//日期
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@blockMonitorImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("吊装人员")) {
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@liftingOpUserImage", imageEntity);//图片
                        }
                    } else if (bean.getContent().equals("吊装指挥")) {
                        //liftingOpUserName
                        PersonSigenerMessageBean messageBean = getOnePersonImageMessage(bean.getListBean());
                        if (messageBean != null && StringUtils.isNotBlank(messageBean.getUrl())) {
                            FileInputStream fis = new FileInputStream(new File(messageBean.getUrl()));
                            byte[] abc = ByteStreams.toByteArray(fis);
                            ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
                            map.put("@liftingCommanderImage", imageEntity);//图片
                        }
                    }
                }
                map.put("cp", currentPhotoList);
            }
        }
        return map;
    }

    private String getDate(Date date) {
        if (date != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(date);
        } else {
            return null;
        }
    }

    //获取签字表个人信息
    private PersonSigenerMessageBean getOnePersonImageMessage(BpWorkSafetySigenerListBean listBean) throws
            IOException {
        PersonSigenerMessageBean bean = new PersonSigenerMessageBean();
        if (listBean != null) {
            List<BpWorkSafetySigenerJsonBean> jsonBeans = listBean.getJsonBeans();
            if (!CollectionUtils.isEmpty(jsonBeans)) {
                //目前默认签名只有一个人
                BpWorkSafetySigenerJsonBean jsonBean = jsonBeans.get(0);
                if (jsonBean != null) {
                    bean.setDate(jsonBean.getDate());
                    if (jsonBean.getBaseAttachmentBean() != null) {
                        Long imageId = jsonBean.getBaseAttachmentBean().getId();
                        BaseImageRepository image = baseImageRespositoryDao.findById(imageId).orElseThrow(() -> new IllegalArgumentException("图片不存在"));
                        bean.setUrl("/home/seekcy/wwyt/wwyt-server/upload/images/" + image.getThumbnailPath());
                    }
                }
            }
        }
        return bean;
    }

    private List<String> getCertNameList(List<BpWorkSafetyCertDto> certNames) {
        List<String> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(certNames)) {
            for (BpWorkSafetyCertDto certDto : certNames) {
                list.add(certDto.getCertName());
            }
        }
        return list;
    }
}
